简体   繁体   中英

get value from different HTML elements that have the same class

I'm wondering how to get value from different HTML elements that have the same class? Taken out of it's context this might look strange but there's a reason the code looks like this.

For example, the HTML code might look something like this:

  $('.b').each(function () { alert('dfd'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea class="ab">Text1</textarea> <textarea class="ab">Text2</textarea> <textarea class="ab">Text3</textarea> <div class="bc">...</div> <div class="bc">...</div> <div class="bc">...</div> 

The alert will execute 6 times as there is a total of 6 elements using class " b ". My question is, is it possible to only alert the values from the textareas and skip the divs? A direct path like " textarea .b ".

Try to this

$('.b') into this $('textarea.b')

$('textarea.b').each(function () {
    alert('dfd');
    });

if you are using this $('.b') means all class .b

if you are using this $('textarea.b') means all textarea with class .b

事实上,选择器textarea.b (没有空格)应该工作正常!

Add textarea to the selector

$('textarea.b').each(function () {
    alert('dfd');
    });

Given your code, you can also use this selector :

$('.a.b').each(function () {
    alert('dfd');
    });

You can loop over the textarea.b as following and access the value:

$('textarea.b').each(function(index, txtArea){
        //accecc the contexted textarea either using $(this) or     
        //$(txtArea)
        var val = $(this).val();
        alert('textarea-'+index+': '+ val)
})

Check the fiddle link here: http://jsfiddle.net/9xmtv3pk/

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