0

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.net/guruhkharisma/9zp9H/

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. Commented Oct 8, 2012 at 9:45
  • Use ids to get the data of both texareas Commented Oct 8, 2012 at 9:45

5 Answers 5

2
var text = "";

jQuery("textarea.message").each(function(){
   text += jQuery(this).val() + "\n";
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thank alot.. I tested and It really work :) jsfiddle.net/guruhkharisma/9zp9H/11
@user1728356 Lol that's the code from my answer actually, so you're welcome :)
1

Try thought = $('textarea').text() i think this should work or thought = $('.message').text();

2 Comments

It doesn't. And even if it did, it still would only work for the first one...if you try and 'get' the value associated with a certain property, jQuery only returns the value of the first matched element.
Try modifying the text in your text area then clicking the link: it doesn't update to reflect any of your changes, it only includes what your hard-coded.
1

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.com/each/

Comments

1

.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);
});​

Comments

0
<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);
 });​

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.