0

I have a problem with (un)checking a checkbox using a keydown and combinating it with mouse click. I have a checkbox with id "check" and heres a part of my jQuery code that is checking and unchecking my checkbox by hitting the space bar:

$(document).keydown(function (e) {
    if (e.keyCode == 32) {
        if ($("#check").is(":checked")) {
            $("#check").prop("checked", false);
        }
        else {
            $("#check").prop("checked", true);
        }
    }
});

Everything works nice when document is loaded. But when I check or uncheck checkbox just by classic mouse click I can't use space bar for (un)checking anymore. Everytime I hit spacebar (after I already clicked on checkbox) checkbox checks and unchecks quickly. For example when it's checked and its in this broken state, hitting space bar results only to checbox being checked again.

Thanks for every idea how to prevent this undesirable behavior.

3 Answers3

1

use .removeAttr("checked") for unchecking and use .attr("checked","checked") for checking the checkbox hope this will work

  • No, he shouldn't use `attr('checked', 'checked')` as there is a difference between property and attribute. Have a look at the documentation http://api.jquery.com/prop/ – damian Oct 29 '13 at 14:22
1

your question is similiar to this jQuery difference between change and click event of checkbox . You need to use the click handler, not keydown in order to capture the keyboard event

Community
  • 1
  • 1
michael truong
  • 321
  • 1
  • 4
1

You can use event.stopImmediatePropagation

Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

Also add this line for crossbrowser support

event = e || window.event;

DEMO

$(document).keydown(function (e) {
    event = e || window.event;
    event.stopImmediatePropagation();

    if (event.keyCode == 32) {
        if ($("#check").is(":checked")) {
            $("#check").prop("checked", false);
        }
        else {
            $("#check").prop("checked", true);
        }
    }
});
damian
  • 5,314
  • 5
  • 34
  • 63