588

I am attempting to set a value in a textarea field using jquery with the following code:

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

The issue is, once this code executes, it is not altering the text in the textarea?

However when performing an alert($("textarea#ExampleMessage").attr("value")) the newly set value is returned?

Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
GONeale
  • 26,302
  • 21
  • 106
  • 149
  • 3
    If the jQuery magic is not working to set val() on – billrichards Oct 25 '17 at 14:31

28 Answers28

968

Have you tried val?

$("textarea#ExampleMessage").val(result.exampleMessage);
enobrev
  • 22,314
  • 7
  • 42
  • 53
  • I think that does the same as attr("value"); – Sophie Alpert Jan 06 '09 at 06:12
  • 5
    mostly true, although val does take the time to make sure the value you're setting is a string, and attr seems to do a bit more magic overall. – enobrev Jan 06 '09 at 06:31
  • 1
    Sorry about the muck around, val() is working. I had tried a different field, and did not re-update the textarea id ref in question. – GONeale Jan 06 '09 at 06:34
  • 65
    Yeah. A textarea doesn't have a value attribute, while an input does. – MDCore Jan 06 '09 at 12:20
  • 14
    Agreed, but val() is setting it in this instance. They [jquery] must determine it's textarea type and set the text. – GONeale Jan 07 '09 at 00:03
  • 18
    textarea has a value (JavaScript) property just like a text input. It doesn't have an HTML `value` attribute, but that doesn't matter, because both `val()` and `attr('value')` write to the JavaScript value property. Note, `attr()` does *not* set HTML attributes! It only sets JavaScript properties, whilst trying to hide the difference for cases like class/className where the name is different. But you will still see the difference for places where the attribute and property do different things, such as in form elements. – bobince Sep 08 '09 at 10:21
  • 1
    None of the variations here are working for me. I wonder what I'm doing wrong. I tried `html("...")` and `attr("innerText", "...")` as well. – i_am_jorf Jan 24 '13 at 22:26
  • 2
    `val(foo)` works for me (jQuery 1.9.1). Using `text(foo)` loses to update textarea content loses the linebreaks on IE, using `val(foo)` preserves them. – Tim Sep 11 '13 at 09:21
  • @BenMosher I tried in JSFiddle with 1.6.4 and 1.7.2 (unfortunately there is no 1.7.1 on JSF), and it worked fine: http://jsfiddle.net/h5y51Lmf/1/ . (uncomment the alerts to see it in action). It could very well be a bug in 1.7.1, but that's a pretty significant bug that I'd be surprised they let through. You might want to make sure you're not somehow otherwise altering the textarea before you try to grab the .val() from it. Also, make sure your selector is only working on a single element, like using an id instead of a class. – enobrev Oct 06 '14 at 14:06
  • @enobrev -- looks like you're right. Must be ghosts on my end. I tried with the CDN version of 1.7.1 and it works in your fiddle. (comment removed for future reader clarity) – Ben Mosher Oct 06 '14 at 14:39
  • @jeffamaphone It happened the same for me also. Whenever I tried setting the textarea's value with $('#someid').val('my value') it didn't work (it was not visible the change). Once I've changed it into $('textarea[id=someid]').val('my value') it instantly worked. – Zsolti Nov 03 '14 at 13:52
  • 1
    This is correct. By the way the `textarea` will not respond to `$("textarea").on('change keyup paste',function(e) {})` events when doing `paste`. But it will be triggered by the `$('textarea').trigger('change');` – loretoparisi Jan 25 '19 at 09:34
82

Textarea has no value attribute, its value comes between tags, i.e: <textarea>my text</textarea>, it is not like the input field (<input value="my text" />). That's why attr doesn't work :)

Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
danivalentin
  • 1,647
  • 12
  • 9
60

$("textarea#ExampleMessage").val() in jquery just a magic.

You should notice that textarea tag using inner html to display and not in value attribute just like input tag.

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

You should use

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

or

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

depend on if you want to display it as html tags or plain text.

CallMeLaNN
  • 8,328
  • 7
  • 59
  • 74
  • 1
    You are correct, textarea doens't have a val or value, and jquery is just doing some magic to make life easier for the developer. – Scott Kirkwood Aug 26 '10 at 00:37
  • 16
    It's not called magic, it's called abstraction. textarea is only 1's and 0's, but all the layers of abstraction in your computer hides that for you. It's okay to point it out, but please don't ask people to downvote other answers for such a reason... :) – Espen Herseth Halvorsen Oct 01 '10 at 14:22
  • 10
    beware - html() executes script tags. – Lincoln B Jan 06 '14 at 00:57
  • 6
    From [jQuery API](http://api.jquery.com/text/) "The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method." – pilot Jul 13 '18 at 15:08
27

Oohh come on boys! it works just with

$('#your_textarea_id').val('some_value');
Alfred
  • 21,058
  • 61
  • 167
  • 249
Mik
  • 289
  • 3
  • 2
18

I think this should work :

$("textarea#ExampleMessage").val(result.exampleMessage);
Jomit
  • 596
  • 3
  • 11
16

On android .val and .html didn't work.

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

did the job.

Cleb
  • 25,102
  • 20
  • 116
  • 151
Dan Ochiana
  • 3,340
  • 1
  • 30
  • 28
  • 2
    From [jQuery API](http://api.jquery.com/text/) "The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method." – pilot Jul 13 '18 at 15:10
  • Yes. But to my surprise, this worked. on .net C# Razor textarea, When I was manipulating dom to add more fields by clicking. I used this to keep existing fields state values $('#id').text($('#id').val()); – Developer Mar 10 '21 at 21:32
  • I needed a way to clear a textarea that was populated after posting the form to process using PHP (a transliteration function). This is the solution that worked. – cheeseus May 08 '22 at 13:41
11

i had the same question so i decided to try it in the current browsers (we're one and a half year later in time after this question), and this (.val) works

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

for

  • IE8
  • FF 3.6
  • FF4
  • Opera 11
  • Chrome 10
Michel
  • 23,085
  • 46
  • 152
  • 242
  • 1
    For the record, one of the exceptional jQuery functionalities is the one of provide browser compatibility, so yes, it's pretty likely that `.val()` will do its magic in several browsers ;) – Diosney Aug 21 '11 at 03:19
8

I had same issue and this solution didn't work but what worked was to use html

$('#your_textarea_id').html('some_value');
Alfred
  • 21,058
  • 61
  • 167
  • 249
dave
  • 81
  • 1
  • 1
  • 3
    no, `html()` is working only once per textarea, next time, you want to dynamically change content of `textarea`, `html()` will not work... – Legionar Dec 19 '14 at 13:49
  • @Legionar then how to handle this case ? – Jawand Singh Oct 03 '18 at 06:24
  • well, this one helped me https://stackoverflow.com/questions/1219860/html-encoding-lost-when-attribute-read-from-input-field/7124052#7124052 using these functions i just set encoded value in textarea using `$('#textarea').val(encodedtext);` – Jawand Singh Oct 03 '18 at 07:02
7

textarea doesn't store values as

<textarea value="someString">

instead, it stores values in this format:

<textarea>someString</textarea>

So attr("value","someString") gets you this result:

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

try $("#textareaid").val() or $("#textareaid").innerHTML instead.

Luka Ramishvili
  • 889
  • 1
  • 11
  • 20
6

There the problem : I need to generate html code from the contain of a given div. Then, I have to put this raw html code in a textarea. When I use the function $(textarea).val() like this :

$(textarea).val("some html like < input type='text' value='' style="background: url('http://www.w.com/bg.gif') repeat-x center;" /> bla bla");

or

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

I had problem with some special character ( & ' " ) when they are between quot. But when I use the function : $(textarea).html() the text is ok.

There an example form :

<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='youremail@gmail.com' /></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>

And javascript/jquery code that don't work to fill the textarea is :

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

Finaly the solution :

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

The trick is wrap your textarea with a span tag to help with the replaceWith function. I'm not sure if it's very clean, but it's work perfect too add raw html code in a textarea.

Fateme Mirjalili
  • 762
  • 7
  • 16
Mathieua
  • 69
  • 1
  • 2
5

Text Area doesnot have value. jQuery .html() works in this case

$("textarea#ExampleMessage").html(result.exampleMessage);
psoni
  • 59
  • 1
  • 2
  • 2
    no, `html()` is working only once per textarea, next time, you want to dynamically change content of `textarea`, `html()` will not work... – Legionar Dec 19 '14 at 13:49
  • and if you did .empty().html('newContent') @Legionar ? – V H Feb 08 '17 at 14:14
5

I think there is missing one important aspect:

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

works only when there is an ID selector (#)

for class selector there is an option to use native value like:

$('.some-text-area')[0].value = 'test';
user2846569
  • 2,752
  • 2
  • 23
  • 24
3

To set textarea value of encoded HTML (to show as HTML) you should use .html( the_var ) but as mentioned if you try and set it again it may (and probably) will not work.

You can fix this by emptying the textarea .empty() and then setting it again with .html( the_var )

Here's a working JSFiddle: 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>
sMyles
  • 2,418
  • 1
  • 30
  • 44
3

Adding to some great answers above, in a case where you using multi-forms and the element NAME is what you want to target.

$('textarea[name=ExampleMessageElName]').val('Some Message here');
gabisajr
  • 146
  • 1
  • 5
3

It works for me.... I have built a face book wall...

Here is the basis of my code:

// SETS MY TEXT AREA TO EMPTY (NO VALUE)
$('textarea#message_wall').val('');
Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
2

I tried with .val() .text() .html() and had some bugs using jQuery to read or set value of a textarea... i endup using native js

$('#message').blur(function() {    
    if (this.value == '') { this.value = msg_greeting; }
});
LPL
  • 16,827
  • 6
  • 51
  • 95
Antony
  • 21
  • 1
2

Just use textarea Id by its type like it:

$("textarea#samplID").val()
2

I've used $(textarea).val/html/text(any_str_var) all worked for me. If you want to be sure that your variable as a string is added to the textarea, you can always concat like so:

$(textarea).val(unknown_var + '')

.val() method is definitely used on textarea - see: https://api.jquery.com/val/

.html() can be used to get or set the contents of any element - see: https://api.jquery.com/html/#html2

.text() is the same as .html except this can be used to set XML content: see - https://api.jquery.com/text/#text-text

You can also read more about how each act upon special characters with each of those links.

2

In my condition i had this input in iframe, any of the above resolve my problem but this :

I just solve it like in this way :

$('#myId')[0].value="MY VALUE";

My input field :

<textarea name="cmyInput" rows="2" cols="20" id="myId" class="nd" ignoreautotab="1"></textarea>
cansu
  • 958
  • 1
  • 12
  • 23
2

You can even use the below snippet.

$("textarea#ExampleMessage").append(result.exampleMessage);
shyamshyre
  • 539
  • 3
  • 5
  • 10
2

We can either use .val() or .text() methods to set values. we need to put value inside val() like val("hello").

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

Check example here: http://www.codegateway.com/2012/03/set-value-to-textarea-jquery.html

Avinash
  • 199
  • 1
  • 2
1

When I had JQuery v1.4.4 in the page, neither of these worked. When injecting JQuery v1.7.1 into my page, it worked finally. So in my case, it was my JQuery version that was causing the issue.

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');
JustBeingHelpful
  • 18,332
  • 38
  • 160
  • 245
1

The accepted answer works for me, but only after I realized I had to execute my code after the page was finished loading. In this situation inline script didn't work, I guess because #my_form wasn't done loading yet.

$(document).ready(function() {
  $("#my_form textarea").val('');
});
pdub23
  • 21
  • 2
0

Using $("textarea#ExampleMessage").html('whatever you want to put here'); can be a good way, because .val() can have problems when you are using data from database.

For example:

A database field named as description has the following value asjkdfklasdjf sjklñadf. In this case using .val() to assign value to textarea can be a tedious job.

StKiller
  • 7,631
  • 10
  • 43
  • 56
0

Just use this code and you will always have the value:

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

So it will check val() and set its value. If val() gets an empty string, NULL, NaN o.s. it will check for html() and then for text()...

Simon
  • 11
0

I've tried to set value / text / html using JQuery but was not successful. So I tried the following.

In this case I was injecting new textarea element to a after DOM created.

 var valueToDisplay= 'Your text here even with line breaks';
 var textBox = '<textarea class="form-control" >'+ valueToDisplay +'</textarea>';
 $(td).html(textBox);

enter image description here

Peck_conyon
  • 221
  • 2
  • 13
0

To edit text inside of textarea through jQuery use $(id).html e.g.

<textarea id="descricao2" name="descricao2" class="form" style="width:600px;height: 130px;"></textarea>

$("#descricao2").html("hello");
0

This works:

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

Remember, the tricky part here is making sure you use the correct ID. And before you use the ID make sure you put # before it.

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
ADL
  • 2,707
  • 1
  • 16
  • 23