views:

303

answers:

2

How do I disable backspace keystroke if anything other than 2 specific input fields are focused on using jquery?

here is my current code (NOW INCLUDING 2 TEXTBOXES):

$(document).keypress(function(e){
  var elid = $(document.activeElement).attr('id');
  if(e.keyCode === 8 && elid != 'textbox1' || elid != 'textbox2'){
      return false;
  };
});

this is not working though....any ideas?

+1  A: 

You're not going to like this answer, but don't do this it breaks the browser, or more accurately, what the user expects their browser to do. The user expects their backspace key to take them back a page, like it does on the other 99.9999% of the web sites. Going against the standard expected behavior for the user is rarely, if ever, a good idea.

Nick Craver
I would completely understand and accept this response if this was going to be a www or even widely used website but this is a specific application used on only 1 machine EVER IN THE WORLD and needs this functionality.
sadmicrowave
@sadmicrowave - Then... `if($(document.activeElement).attr('id') != 'textbox')` assuming `textbox` is the ID of the element you want it to occur in.
Nick Craver
@Nick Craver - thanks for the help, that worked perfectly for one textbox, but what if I wanted to apply this to 2 textboxes? I've elaborated in my original post above....
sadmicrowave
Nick Craver
+1  A: 

I think this would do the trick:

$(document).keypress(function(e){ 
  var elid = $(document.activeElement).hasClass('textInput'); 
  if(e.keyCode === 8 && !elid){ 
      return false; 
  }; 
});

assuming that the textboxes has the class 'textInput'.

Haven't tried it out, but hasClass returns true if the element has the class in question as one of it's classes.

Charlie boy