简体   繁体   中英

Javascript - Get Multiple textarea values with jquery

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/

var text = "";

jQuery("textarea.message").each(function(){
   text += jQuery(this).val() + "\n";
})

尝试thought = $('textarea').text()我认为这应该工作或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.com/each/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM