vindemi vindemi - 28 days ago 8
Javascript Question

Get array of custom attribute values by finding class and checked checkbox type

I have few checkboxes and those elements contain a custom attribute named

data-id
. For example:

<input class="testCheckbox" icheck="" ng-model="Model" data-id="57e3"type="checkbox">


I want to receive an array of ids by finding it by class name and type of the element. Currently I have something like this and it works:

var testIds = [];
$('input.testCheckbox[type="checkbox"]:checked').each(function() {
testIds.push($(this).attr("data-id"))
});


I am wondering if there is inline function in jQuery which can return the same result? I've tried with this code but it only returns first value:

console.log($('input.testCheckbox[type="checkbox"]:checked').attr("data-id"));


I do not know what I am doing wrong? Best regards.

Answer

There's no inline function to do this, but you can shorten your code by using map() instead:

var testIds = $('input.testCheckbox[type="checkbox"]:checked').map(function() {
    return $(this).data('id');
}).get();
Comments