Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: how to get datas from elements without looping?

Tags:

jquery

$('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]

like image 509
yarek Avatar asked Feb 26 '26 08:02

yarek


1 Answers

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>
like image 80
Suresh Atta Avatar answered Feb 27 '26 23:02

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!