Jquery: how to get data from elements without loops?

     

$('input:checkbox:checked')

      

Provides me an array (3 elements) of the checked input as an array.

$('input:checkbox:checked').data('userid')

      

This will give me the data id from which the FIRST login was verified. result = 1

Is there a way to get data from ALL checked inputs without having to write a loop? for example: [1,2,3]

+3


source to share


2 answers


Not. It is impossible to get values ​​without loops on them.

You can avoid the traditional cycle. If you are looking for a cleaner solution use the map function




var result = $('input:checkbox:checked').map(function() {
    return $(this).attr('userid');
}).get();
console.log(result);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" userid="1" name="vehicle" value="Car" checked> I have a car<br>
  
  <input type="checkbox" userid="2" name="vehicle" value="Car" checked> I have two legs<br>
      

Run code


+3


source


You can add your own function to jquery to avoid code duplication. Try the following:



$.fn.extend({
           pluckAttr: function (attr) {
              return $(this).map(function(){
                   return $(this).attr(attr);
               }).get();
           }
       });
$('input:checkbox:checked').pluckAttr('data-userid');

      

0


source







All Articles