val () vs. text () para textarea
Estoy usando jQuery, y me pregunto si debería usar val() o text() (u otro método) para leer y actualizar el contenido de un textarea.
He intentado ambos y he tenido problemas con ambos. Cuando uso text () para actualizar textarea, los saltos de línea (\n) no funcionan. Cuando uso val () para recuperar el contenido de textarea, el texto se trunca si es demasiado largo.
3 answers
La mejor manera de establecer / obtener el valor de un área de texto es .val()
, .value
método.
.text()
internamente usa el método .textContent
(o .innerText
para IE) para obtener el contenido de un <textarea>
. Los siguientes casos de prueba ilustran cómo text()
y .val()
se relacionan entre sí:
var t = '<textarea>';
console.log($(t).text('test').val()); // Prints test
console.log($(t).val('too').text('test').val()); // Prints too
console.log($(t).val('too').text()); // Prints nothing
console.log($(t).text('test').val('too').val()); // Prints too
console.log($(t).text('test').val('too').text()); // Prints test
El value
la propiedad , utilizada por .val()
siempre muestra el valor visible actual, mientras que el valor devuelto por text()
puede ser incorrecto.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-14 03:26:57
.val()
siempre funciona con elementos textarea
.
.text()
funciona a veces y falla otras veces! No es confiable (probado en Cromo 33)
Lo mejor es que .val()
también funciona a la perfección con otros elementos de formulario (como input
), mientras que .text()
falla.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-24 07:07:58
Seleccione <textarea>
por nombre de atributo en lugar de id.
<textarea id="message" name="message"></textarea>
<script>
jQuery("textarea[name='message']").val();
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-12 14:27:50