0

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.

Mr.Singh
  • 1,421
  • 6
  • 21
  • 46
  • Hint. `[type="checkbox"]` is used to find elements that have `type="checkbox"` on them. – Taplar Jun 01 '20 at 16:29
  • Yes, I am aware of this. And I have already tried this. But that way i have loop out each and every checkbox. I was looking a way to bypass that and straight to the checkbox with the attribute. – Mr.Singh Jun 01 '20 at 17:21
  • Does this help? https://stackoverflow.com/questions/4146502/jquery-selectors-on-custom-data-attributes-using-html5 – Nikki9696 Jun 01 '20 at 17:59
  • No @Nikki9696, If i was adding the data attribute in the tag then it would have worked. But, I am working with data property. – Mr.Singh Jun 01 '20 at 18:47

1 Answers1

1

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

Hagai Wild
  • 1,904
  • 11
  • 19