Advertisement
Advertisement


Set value of textarea in jQuery


Question

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?

2016/04/28
1
533
4/28/2016 11:48:11 PM

Accepted Answer

Have you tried val?

$("textarea#ExampleMessage").val(result.exampleMessage);
2009/01/06
890
1/6/2009 6:10:17 AM

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 :)

2010/09/16

$("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.

2010/05/07

Oohh come on boys! it works just with

$('#your_textarea_id').val('some_value');
2012/08/18

I think this should work :

$("textarea#ExampleMessage").val(result.exampleMessage);
2009/01/06

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
2011/04/06

Source: https://stackoverflow.com/questions/415602
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]