lundi 27 juillet 2015

javascript checkbox .click() causes following code not to run

I am writing some Javascript for an Apache Wicket page and am trying to create a "Select All" checkbox that, when checked, will check all of the other checkboxes and then disable them. Similarly, when dechecked, it will enable and uncheck all of the checkboxes. This checkbox will not be updated by the rest (that is, selecting all of the other checkboxes will not select the Select All box).

I can accomplish what I want using checkbox.checked = selectAll.checked but it doesn't seem to pass in a click event, which I need for some functionality in Wicket. Using checkbox.click() gives me the click events I need but doesn't seem to run after re-enabling the checkboxes.

Any idea why using .click() isn't working as expected?

var selectAll = document.getElementById("all");

function checkbox_changed() {
  checkboxes = document.getElementsByName('foo');

  for (var i in checkboxes) {
    var checkbox = checkboxes[i];

    checkbox.disabled = false;

    if (checkbox.checked !== selectAll.checked) {
      //checkbox.checked = selectAll.checked;
      checkbox.click();
    }

    if (selectAll.checked) {
      checkbox.disabled = true;
    }
  }
}
<form>
  <input type="checkbox" id="all" onchange="checkbox_changed()">Select All
  <br>
  <br>
  <input type="checkbox" name="foo">One
  <br>
  <input type="checkbox" name="foo">Two
  <br>
  <input type="checkbox" name="foo">Three
  <br>
  <input type="checkbox" name="foo">Four
  <br>
</form>

In case its easier, here is a jsfiddle of the above: http://ift.tt/1U2s5BL




Aucun commentaire:

Enregistrer un commentaire