简体   繁体   中英

.val() alternative that gets the current value of all elements in the set of matched elements

I have 3 select elements and I'm using $(".select-elem select").val() to get the value of each select element in an array but it returns the value of only the first element in the set of matched elements. For example, if a user selects '2' for the first select element, '3' for the second, and '4' for the third, the val() function returns 2 instead of [2,3,4] . Is there a function that would return an array containing values of all three select elements?

<td class="select-elem">
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</td>
<td class="select-elem">
<select>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</td>
<td class="select-elem">
<select>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</td>

Use map methods for this:

var values = $(".select-elem select").map(function() {
    return $(this).val();
}).get();

Create your own jquery method and use it wherever you need, find the following code

//create jquery method arrVal which returns array of values
$.fn.arrVal = function () {
  var valArr = [];
  $(this).each(function(){
    valArr.push($(this).val())
  })
  return valArr;
}

//call arrVal method
$('select').arrVal()

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