Reputation: 12034
$('input:checkbox:checked')
Provides me an array (3 items) of checked input as an array.
$('input:checkbox:checked').data('userid')
This provide me the data-userid of the FIRST checked input. result = 1
Is there a way to get datas of ALL checked inputs WITHOUT having to write a loop ? ex: [1,2,3]
Upvotes: 3
Views: 931
Reputation: 2604
You can add your own function to jquery to avoid code duplication. Try this:
$.fn.extend({
pluckAttr: function (attr) {
return $(this).map(function(){
return $(this).attr(attr);
}).get();
}
});
$('input:checkbox:checked').pluckAttr('data-userid');
Upvotes: 0
Reputation: 121998
No. It is not at all possible to get values without looping on them.
You can avoid traditional loop. If you looking for a cleaner solution use 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>
Upvotes: 3