Select all checkbox in primefaces

769 views Asked by At

The requirement of the logic is:
- I have a list of checkbox (I use p:selectManyCheckbox).
- I also have a checkbox which if it is checked, other check box should be checked also (I use p:selectBooleanCheckbox for this)
- Let me give an specific example, now I have 3 checkboxes:
+ Select all
+ Item 1
+ Item 2

If 'select all' is checked, 'item 1' and 'item 2' are checked. If 'select all' is unchecked, 'item 1' and 'item 2' are unchecked.
If one of 'item 1' or 'item 2' is unchecked, 'select all' should be unchecked. If both 'item 1' and 'item 2' are checked, 'select all' should be checked automatically.

To implement that, I use javascript for onchange event of every checkbox.
For select all, onchange = updateOtherCheckboxes(otherCheckboxes, selectAllCheckbox)

function updateCheckboxes(otherCheckboxes, selectAllCheckbox) {
 otherCheckboxes.inputs.each(function() {
  if (selectAllCheckbox.isChecked()) {
   $(this).prop('checked', false);
  } else {
   $(this).prop('checked', true);
  }
  $(this).trigger('click');
 });
}

For other checkboxes, onchange = updateSelectAllCheckbox(otherCheckboxes, selectAllCheckbox)

function updateSelectAllCheckbox(otherCheckboxes, selectAllCheckbox) {
 var notAllCheckboxesChecked = false;
 otherCheckboxes.inputs.each(function() {
  if ($(this).is(':checked') == false) {
   notAllCheckboxesChecked = true;
   return false;
  }
 });
 if (notAllCheckboxesChecked && selectAllCheckbox.input.is(':checked') == true) {
  selectAllCheckbox.input.trigger('click');
 } else if (!notAllCheckboxesChecked && selectAllCheckbox.input.is(':checked') == false) {
  selectAllCheckbox.input.trigger('click');
 }
}

The problem here is that, in updateCheckboxes() function, other checkboxes's click event are triggered and updateSelectAllCheckbox will be called, but I don't want that. So how can I prevent updateSelectAllCheckbox() function to be invoked in updateCheckboxes() function after I trigger the click event.

1

There are 1 answers

8
Sven Hakvoort On

You don't have to call $(this).trigger('check') because this will fire the click event, your earlier code $(this).prop('checked', true) already makes sure the checkbox will be checked so you don't have to fire the click event anymore.

If the $(this).prop('checked', true) does not work you could also try: $(this).attr('checked', true);