简体   繁体   中英

How to prevent checkbox being checked from label click if it is indeterminate?

How would I stop a click event from a label associated to a checkbox if the checkbox is indeterminate?

I have attempted the following, but to no avail:

el.parent().find('.arena-custom-label').click(function ( event ) {
    if (el.is(':indeterminate')) {
        event.preventDefault();
        el.attr('indeterminate', false);
        el.removeClass('indeterminate');
        dataGrid.find('.ag.gr:checked').trigger('click');
    } else {
        el.change(function () {
            if (el.is(':checked')) {
                dataGrid.find('tbody .ag.gr:not(:checked)').trigger('click');
            } else {
                dataGrid.find('tbody .ag.gr:checked').trigger('click');
            }
        });
    }
});

el being the checkbox itself.

The goal is while this check box is indeterminate, upon the associated label click all I want it to do is go out of indeterminate and to unchecked. Then I will trigger all checked checkboxes in a table to go unchecked as well.

The problem is that when I click the indeterminate checkbox label, it causes it to go checked resulting in all unchecked checkboxes to go checked. The opposite of what I want.

indeterminate is a prop , not an attribute so you should use jquery.prop to update:

el.parent().find('.arena-custom-label').click(function ( event ) {
  if (el.is(':indeterminate')) {
    event.preventDefault();
    el.prop('indeterminate', false);
    el.removeClass('indeterminate');
    dataGrid.find('.ag.gr:checked').trigger('click');
  } else {
    el.change(function () {
      if (el.is(':checked')) {
          dataGrid.find('tbody .ag.gr:not(:checked)').trigger('click');
      } else {
          dataGrid.find('tbody .ag.gr:checked').trigger('click');
      }
    });
  }
});

See here and here for explanations.

Here is a fiddle with a vanilla JS demo.

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