JuanPablo
JuanPablo

Reputation: 24764

textarea doesn't update

With jQuery, I added a textarea

$('#description').append('<textarea rows="8" cols="40">test</textarea>');

Ok, and I change "test" text to "test 01". But, when I try

 var cadena = $('#description').text();
 alert(cadena);

I get "test" and not "test 01". Why?

Upvotes: 9

Views: 17950

Answers (4)

Amar Palsapure
Amar Palsapure

Reputation: 9680

User .val() instead of .text().

If you have only one text area appended you can do

 var cadena = $('#description textarea:first-child').val();

Test Case : http://jsfiddle.net/UzK59/

OR

If you are appending more than one text area

 var counter = 0;
 $('#description').append('<textarea id="textArea'+ counter +'" rows="8" cols="40">test</textarea>');
 counter++;

and then

 $('#textArea' + counter).val(); //Considering counter is 0 (Zero) here

Test Case : http://jsfiddle.net/UzK59/1/

To set value you can do

 $('#textArea' + counter).val('New Value')

Hope this helps you.

Upvotes: 3

Josh Darnell
Josh Darnell

Reputation: 11433

It really looks like you would want to do this:

$('#description').append('<textarea id="newTextArea" rows="8" cols="40">test</textarea>');¬ 

And then this:

var cadena = $('#newTextArea').text();
alert(cadena);

Otherwise, you're just appending the textarea inside of whatever #description is, and then trying to get the .text value of...all that (whatever it is).

If you add an id to the textarea, you can be more specific with your selection, and get the text value that you're looking for.

Upvotes: 3

nnnnnn
nnnnnn

Reputation: 150030

Like it says on the .text() doco page, "To set or get the text value of input or textarea elements, use the .val() method."

You don't say how you change the text, but you should be doing this:

$('#description textarea').val("test 01");        // change the text

var cadena = $('#description textarea').val();   // retrieve the current text

Noting that "#description" is the textarea's container, and you need to select the textarea itself to get the value. Of course the above won't work if you have more than one textarea in that container, so it would be better if you could assign the new textarea an id an then select based on that.

Upvotes: 8

gdoron
gdoron

Reputation: 150253

give the textarea an id and then change it's value with the val function:

$('#description').append('<textarea id="xxx" rows="8" cols="40">test</textarea>');    
$('#xxx').val('test01');

//... later on
alert($('#xxx').val());

Upvotes: 10

Related Questions