简体   繁体   中英

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.

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();

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