0

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.

$("div#types input").focus(function(){
  window.onkeydown = function(e){
    return !(e.keyCode == 8);
};
Coral Doe
  • 1,925
  • 3
  • 19
  • 36
sadmicrowave
  • 39,964
  • 34
  • 108
  • 180
  • Why are you trying to disrupt the typical browser UI pattern? I fervently reject that this is necessary, unless you are building an extremely specialized web application where keyboard shortcuts are common. – Matchu Apr 14 '10 at 16:23
  • that is exactly what I'm doing. This is not a webpage for the general public. This application will only be used on 2 computers EVER and needs this functionality. – sadmicrowave Apr 14 '10 at 16:26

1 Answers1

4

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
  • 4,983
  • 6
  • 42
  • 66