Establecer el valor de textarea en jQuery


Estoy intentando establecer un valor en un campo textarea usando jquery con el siguiente código:

$("textarea#ExampleMessage").attr("value", result.exampleMessage);

El problema es que, una vez que este código se ejecuta, ¿no está alterando el texto en el área de texto?

Sin embargo, cuando se realiza un alert($("textarea#ExampleMessage").attr("value")) el nuevo valor establecido se devuelve?

Author: Ryan Wheale, 2009-01-06

23 answers

¿Has probado val?

$("textarea#ExampleMessage").val(result.exampleMessage);
 788
Author: enobrev,
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
2009-01-06 06:10:17

Textarea no tiene atributo de valor, su valor viene entre etiquetas, es decir: <textarea>my text</textarea>, no es como el campo de entrada (<input value="my text" />). Es por eso que attr no funciona :)

 68
Author: danivalentin,
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
2010-09-16 22:20:36

$("textarea#ExampleMessage").val() en jquery solo una magia.

Debe notar que textarea etiqueta usando html interno para mostrar y no en el atributo de valor al igual que la etiqueta de entrada.

<textarea>blah blah</textarea>
<input type="text" value="blah blah"/>

Debe usar

$("textarea#ExampleMessage").html(result.exampleMessage)

O

$("textarea#ExampleMessage").text(result.exampleMessage)

Depende de si desea mostrarlo como etiquetas html o texto sin formato.

 44
Author: CallMeLaNN,
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
2010-05-07 11:52:33

Creo que esto debería funcionar :

$("textarea#ExampleMessage").val(result.exampleMessage);
 13
Author: Jomit,
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
2009-01-06 06:19:29

Oohh vamos chicos! funciona solo con

$('#your_textarea_id').val('some_value');
 13
Author: Mik,
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-08-18 12:14:27

Tenía la misma pregunta, así que decidí probarlo en los navegadores actuales (estamos un año y medio más tarde en el tiempo después de esta pregunta), y esto (.val) funciona

$("textarea#ExampleMessage").val(result.exampleMessage); 

Para

  • IE8
  • FF 3.6
  • FF4
  • Opera 11
  • Cromo 10
 10
Author: Michel,
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
2011-04-06 07:53:19

Tuve el mismo problema y esta solución no funcionó, pero lo que funcionó fue usar html

$('#your_textarea_id').html('some_value');
 8
Author: dave,
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-08-18 12:13:36

En android .val y .html no funcionó.

$('#id').text("some value")

Hizo el trabajo.

 7
Author: Dan Ochiana,
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
2018-07-02 10:04:38

Ahí está el problema : Necesito generar código html a partir del contenido de un div dado. Entonces, tengo que poner este código html en bruto en un área de texto. Cuando uso la función text (textarea).val () así:

$(área de texto).val ("algunos html como bla bla");

O

$('#idTxtArGenHtml').val( $('idDivMain').html() );

Tuve problemas con algunos carácter especial ( & '" ) cuando están entre quot. Pero cuando uso la función : text (textarea).html() el texto está bien.

Hay una forma de ejemplo:

<FORM id="idFormContact" name="nFormContact" action="send.php" method="post"  >
    <FIELDSET id="idFieldContact" class="CMainFieldset">
        <LEGEND>Test your newsletter&raquo; </LEGEND> 
        <p>Send to &agrave; : <input id='idInpMailList' type='text' value='[email protected]' /></p>
        <FIELDSET  class="CChildFieldset">
            <LEGEND>Subject</LEGEND>
            <LABEL for="idNomClient" class="CInfoLabel">Enter the subject: *&nbsp</LABEL><BR/>
          <INPUT value="" name="nSubject" type="text" id="idSubject" class="CFormInput" alt="Enter the Subject" ><BR/>
    </FIELDSET>
    <FIELDSET  class="CChildFieldset">
        <INPUT id="idBtnGen" type="button" value="Generate" onclick="onGenHtml();"/>&nbsp;&nbsp;
          <INPUT id="idBtnSend" type="button" value="Send" onclick="onSend();"/><BR/><BR/>
            <LEGEND>Message</LEGEND>
                <LABEL for="idTxtArGenHtml" class="CInfoLabel">Html code : *&nbsp</LABEL><BR/>
                <span><TEXTAREA  name="nTxtArGenHtml" id="idTxtArGenHtml" width='100%' cols="69" rows="300" alt="enter your message" ></TEXTAREA></span>
        </FIELDSET>
    </FIELDSET>
</FORM>

Y el código javascript / jquery que no funciona para llenar el área de texto es:

function onGenHtml(){
  $('#idTxtArGenHtml').html( $("#idDivMain").html()  );
}

Finalmente la solución:

function onGenHtml(){
  $('#idTxtArGenHtml').html( $("#idDivMain").html() );
  $('#idTxtArGenHtml').parent().replaceWith( '<span>'+$('#idTxtArGenHtml').parent().html()+'</span>');
}

El truco es envolver su área de texto con una etiqueta span para ayudar con la función replaceWith. No estoy seguro de si es muy limpio, pero es un trabajo perfecto también agregar código html sin procesar en un área de texto.

 5
Author: Mathieua,
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
2011-06-02 18:09:22

El área de texto no tiene valor. jQuery .html () funciona en este caso

$("textarea#ExampleMessage").html(result.exampleMessage);
 4
Author: user2989278,
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
2013-12-04 07:59:25

Textarea no almacena valores como

<textarea value="someString">

En su lugar, almacena valores en este formato:

<textarea>someString</textarea>

Así que attr("value","someString") te da este resultado:

<textarea value="someString">someOLDString</textarea>.

Intenta $("#textareaid").val() o $("#textareaid").innerHTML en su lugar.

 3
Author: Luka Ramishvili,
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-03-19 14:49:15

Lo intenté con .val() .text() .html() y tenía algunos errores utilizando jQuery para leer o establecer el valor de un textarea... i endup usando js nativo

$('#message').blur(function() {    
    if (this.value == '') { this.value = msg_greeting; }
});
 2
Author: Antony,
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
2011-10-09 12:59:53

Funciona para mí.... He construido un muro de facebook...

Aquí está la base de mi código:

// SETS MY TEXT AREA TO EMPTY (NO VALUE)
$('textarea#message_wall').val('');
 2
Author: Edgar Villegas Alvarado,
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-02-24 20:05:18

Podemos usar .val () or .métodos text () para establecer valores. necesitamos poner valor dentro de val () como val("hello").

  $(document).ready(function () {
    $("#submitbtn").click(function () {
      var inputVal = $("#inputText").val();
      $("#txtMessage").val(inputVal);
    });
  });

Comprobar ejemplo aquí: http://www.codegateway.com/2012/03/set-value-to-textarea-jquery.html

 2
Author: Avinash,
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-03-28 15:29:34

Para establecer el valor textarea de HTML codificado (para mostrar como HTML) debe usar .html( the_var ) pero como se mencionó si intenta configurarlo nuevamente, puede (y probablemente) no funcionará.

Puede arreglar esto vaciando el textarea .empty() y luego configurándolo de nuevo con .html( the_var )

Aquí hay un JSFiddle que funciona: https://jsfiddle.net/w7b1thgw/2 /

jQuery(function($){
    
    $('.load_html').click(function(){
        var my_var = $(this).data('my_html');
        $('#dynamic_html').html( my_var ); 
    });
    
    $('#clear_html').click(function(){
        $('#dynamic_html').empty(); 
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="dynamic_html"></textarea>
<a id="google_html" class="load_html" href="#" data-my_html="&lt;a href=&quot;google.com&quot;&gt;google.com&lt;/a&gt;">Google HTML</a>
<a id="yahoo_html" class="load_html" href="#" data-my_html="&lt;a href=&quot;yahoo.com&quot;&gt;yahoo.com&lt;/a&gt;">Yahoo HTML</a>
<a id="clear_html" href="#">Clear HTML</a>
 2
Author: sMyles,
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
2015-06-02 20:19:54

La respuesta aceptada funciona para mí, pero solo después de darme cuenta de que tenía que ejecutar mi código después de que la página terminara de cargarse. En esta situación, el script en línea no funcionó, supongo que porque #my_form aún no había terminado de cargarse.

$(document).ready(function() {
  $("#my_form textarea").val('');
});
 1
Author: pdub23,
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-03-19 04:54:06

Incluso puedes usar el siguiente fragmento.

$("textarea#ExampleMessage").append(result.exampleMessage);
 1
Author: shyamshyre,
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-03-19 14:48:14

Cuando tenía jQuery v1.4.4 en la página, ninguno de estos funcionaba. Al inyectar jQuery v1.7.1 en mi página, finalmente funcionó. Así que en mi caso, fue mi versión de jQuery que estaba causando el problema.

Id = = > textareaid

======================

var script1 = document.createElement("script");
script1.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
document.body.appendChild(script1);

var script2 = document.createElement("script"); 
script2.type = "text/javascript"; 
script2.innerHTML = "var $jq171 = $.noConflict();"; 
document.body.appendChild(script2);

$jq171('#textareaid').val('xxx');
 1
Author: MacGyver,
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-04-12 21:09:50

Simplemente use textarea Id por su tipo como:

$("textarea#samplID").val()
 1
Author: S.Mohamed Mahdi Ahmadian zadeh,
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
2016-10-09 08:47:55

Simplemente use este código y siempre tendrá el valor:

var t = $(this); var v = t.val() || t.html() || t.text();

Así que comprobará val() y establecerá su valor. Si val() obtiene una cadena vacía, NULL, NaN o.s. buscará html () y luego text ()...

 0
Author: Simon,
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
2011-02-15 11:57:04

Esto funciona:

var t = $('#taCommentSalesAdministration');
t.val('Hi');

Recuerde, la parte complicada aquí es asegurarse de usar el ID correcto. Y antes de usar el ID, asegúrese de poner # antes de él.

 0
Author: ADL,
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
2011-11-22 18:33:23

Usar $("textarea#ExampleMessage").html('whatever you want to put here'); puede ser una buena manera, porque .val() puede tener problemas cuando se utilizan datos de la base de datos.

Por ejemplo:

Un campo de base de datos llamado description tiene el siguiente valor asjkdfklasdjf sjklñadf. En este caso usando .val () asignar valor a textarea puede ser un trabajo tedioso.

 0
Author: user306265,
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
2011-12-01 15:47:02

Creo que falta un aspecto importante:

$('#some-text-area').val('test');

Funciona solo cuando hay un selector de ID (#)

Para el selector de clase hay una opción para usar un valor nativo como:

$('.some-text-area')[0].value = 'test';
 0
Author: user2846569,
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-07-14 11:57:31