views:

403

answers:

1

I have an HTML table, and each row has a checkbox for selecting or deselecting its row. Whenever a checkbox changes value, I need to add or remove highlighting to the row and also ensure that the page's submit button is only enabled when at least one row is selected and disabled otherwise.

The checkbox event handler is defined by the following function:

function getCheckboxCallback() {
  return function () {
    var parentRow = getParentRow(this);
    if (!parentRow) {
      return;  // No parent row found; abort
    }

    // Adjust the appearance of the row
    setSelected(parentRow, this.checked);

    // Count the number of selected table rows, and disable the submit
    // button whenever no rows are selected
    enforceInvariants();

    return true;
  };
}

Elsewhere in the same module, the checkboxes are given the event handlers:

checkbox.onchange = getCheckboxCallback();
checkbox.onclick = getCheckboxCallback();  // alleged IE fix

I'm working in Windows XP, and everything works fine in both Firefox 3 and Opera 9. However, IE 7 does not handle keyboard interaction well (mouse interaction works fine).

The problem is that if a checkbox has the focus and I hit the spacebar, the checkbox doesn't get checked -- instead it gets half checked (it has the same shadowed appearance that it would get immediately after a mousedown). I have to press the spacebar a second time to actually check the box. Similarly, it requires two key presses to uncheck it. Oddly enough, if I hold down the spacebar for a few moments, then a single press works as expected.

Can anyone explain what is going on here? Is there something I'm doing wrong in the JavaScript code that is causing this behavior? How can I fix this?

A: 

Unfortunately, IE handles onchange differently than other browsers. IE interprets it to mean "on blur after change". Note that while this isn't very useful, it is technically correct according to the spec: "The onchange event occurs when a control loses the input focus and its value has been modified since gaining focus"

You can try using the IE-only event "onpropertychange".

Reference: http://lhorie.blogspot.com/2007/04/fixing-ie7-onchange-bug-on-checkboxes.html

BarelyFitz
But how does that account for the fact that the spacebar presses are not causing the checkbox to be checked?
Bobby Eickhoff
I can't explain that behavior. You might want to try adding a keydown event on the checkbox, and examining the behavior using a debugger, or using the keydown event to check for a spacebar press (event.keyCode === 32).
BarelyFitz