jquerycheckboxtoggleswitching

jQuery: find elements where data attribute is has a specific value


I have a master checkbox Select all along with a button to revert back to their original state to which there were loaded with. After the page is loaded I bind a data property to each of the checkboxes that if there were loaded as checked or un-checked.

$('input[type="checkbox"]').each((i, e) => {
    if($(e).is(':checked'))
       $(e).data('default', true);
});

$('.js-select-all').on('mouseup', () => {
    $('input[type="checkbox"]').prop('checked', true);
});

I need to find the checkboxes where data property called default is true and mark them checked again.

$('.js-revert').on('mouseup', () => {
    $('input[type="checkbox"]').data('default', true).prop('checked', true);
});

I know it can be done with each loop and a condition. But the thing is that I'll have to go through all the checkboxes to do so. Therefore, I am looking for a faster way as there are already dozens of checkboxes in the application.


Solution

  • If you're using just jQuery, there's no faster way to check the .data() stored in the checkboxes besides iterating over all of them.

    But incase you're using jQueryUI you can use the :data() selector presented here:

    https://api.jqueryui.com/data-selector/

    which then you can use

    $(':checkbox:data(default)').prop('checked', true);