views:

348

answers:

1

How do I disable the backspace button when input checkboxes are focused on in jQuery? When checkboxes are focused on and I press backspace (keycode=8) the browser thinks I'm trying to go back a page and uses backspace as a history.go(-1) command.

ADDITION DETAILS--- I've added this--to no avail:

$("div#types input").focus(function(){ window.onkeydown = function(e){ return !(e.keyCode == 8); };

+2  A: 

Well this will stop the backspace button at all times from navigating back:

$(document).keydown(function(e) {
  if (e.keyCode === 8)
  {
     return false;
  }
});

Now to figure out how to run this only when checkboxes are focused...

Edit:

The problem with figuring out if a checkbox has focus is that it only gets focus if it is tabbed to or actually set in code. If it is clicked it is checked but it actually does not focus (at least in chrome/safari). This all depends on how you set the focus.

Edit 2:

To make your checkbox have focus when it is clicked, just add this:

$('input[type=checkbox]').click(function() {
   $(this).focus();
});

...so putting it all together, this would have the checkbox focus on click and stop the backspace button when a checkbox has focus (all inside $(document).ready function of course):

$(document).keydown(function(e) {
    if (e.keyCode === 8 && $('input[type=checkbox]:focus').size() > 0)
    {
       return false;
    }
});

$('input[type=checkbox]').click(function() {
    $(this).focus();
});
ryanulit
any suggestions on how to fix this?
sadmicrowave
Edited my answer.
ryanulit