I'm newbie with jQuery. I Want to get value from these two textarea, I have html like this and jquery below :
Html :
<pre>
<a id="send-thoughts" href="">Click</a>
<textarea id="message1" class="message">Hello</textarea>
<textarea id="message2" class="message">World</textarea>
</pre>
jQuery:
jQuery("a#send-thoughts").click(function() {
var thought= jQuery("textarea.message").val();
alert(thought);
});
Why only one value show up ? and how to get two value of textarea ?
/
I'm newbie with jQuery. I Want to get value from these two textarea, I have html like this and jquery below :
Html :
<pre>
<a id="send-thoughts" href="">Click</a>
<textarea id="message1" class="message">Hello</textarea>
<textarea id="message2" class="message">World</textarea>
</pre>
jQuery:
jQuery("a#send-thoughts").click(function() {
var thought= jQuery("textarea.message").val();
alert(thought);
});
Why only one value show up ? and how to get two value of textarea ?
http://jsfiddle/guruhkharisma/9zp9H/
Share Improve this question asked Oct 8, 2012 at 9:43 guruhguruh 953 silver badges12 bronze badges 2- 2 Because even if the jquery selector has two matches the val() method can only serve the value of one match. So the first match is used. – arkascha Commented Oct 8, 2012 at 9:45
- Use ids to get the data of both texareas – Wearybands Commented Oct 8, 2012 at 9:45
5 Answers
Reset to default 2var text = "";
jQuery("textarea.message").each(function(){
text += jQuery(this).val() + "\n";
})
Try thought = $('textarea').text()
i think this should work
or thought = $('.message').text();
Use the each()
method.
jQuery("a#send-thoughts").click(function() {
jQuery("textarea.message").each(function() {
var thought= $(this).val();
alert(thought);
});
});
Check the online doc for more information: http://api.jquery./each/
.val()
, like all the jQuery getters, returns the value of the first matched form-input element. You will have to use a .each()
loop and concatenate the values:
jQuery("a#send-thoughts").click(function() {
var thought = '';
jQuery("textarea.message").each(function() {
thought += $(this).val() + ' ';
});
alert(thought);
});
<pre>
<a id="send-thoughts" href="">Click</a>
<textarea id="message1" class="message1">Hello</textarea>
<textarea id="message2" class="message2">World</textarea>
</pre>
jQuery:
jQuery("a#send-thoughts").click(function() {
var thought1= jQuery("textarea.message1").val();
alert(thought1);
var thought2= jQuery("textarea.message2").val();
alert(thought2);
});