简体   繁体   中英

Get all select values per div with multiple divs with same classname

Is there a way to get an array of all the selected values inside a div with a particular class name when having more than one div with the same class name?

<div class="mydiv">
<select name="first">
     <option value="1">One</option>
     <option value="2">Two</option>
</select>
<select name="second" ">
     <option value="1">One</option>
     <option value="2">Two</option>
</select> </div>

<div class="mydiv">
<select name="first">
     <option value="1">One</option>
     <option value="2">Two</option>
</select>
<select name="second" ">
     <option value="1">One</option>
     <option value="2">Two</option>
</select> </div>

If i do this: $(".mydiv").each(function (){ });

I will be looping(twice in total as I have two divs with class mydiv) through both divs which is what I want. Now I would like to get the selected values in each div for each select(first and second).

You can use map() .

Following assumes you want a sub array for each <div>

 let res = $('.mydiv').map(function(){ return [$(this).find('select').map(function(){ return $(this).val() }).get()] }).get() console.log(res) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="mydiv"> <select name="first"> <option value="1" selected>One</option> <option value="2">Two</option> </select> <select name="second"> <option value="1">One</option> <option value="2" selected>Two</option> </select> </div> <div class="mydiv"> <select name="first"> <option value="1">One</option> <option value="2" selected>Two</option> </select> <select name="second"> <option value="1">One</option> <option value="2" selected>Two</option> </select> </div> 

For a flat array just do :

let res = $('.mydiv select').map(function(){
   return $(this).val();
}).get();

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