codepuppy
codepuppy

Reputation: 1140

jQuery Prevent Default - doesn't appear to work in some circumstances

I have used event.preventDefault() and event.stopPropagation() in various places but it always seems to be a bit of a struggle to get it to work.

I have now hit a wall with the instance:-

$("#existing_Flavours").on("keydown", function(event){
    switch(event.which){
        case 9:
            //tab called permit
            break;
        default:
            event.preventDefault();
            event.stopPropagation();
    } // end switch
});

I want the tab key to work but nothing else.

Been round this endlessly and no matter what I cannot stop normal key strokes from occurring.

Upvotes: 0

Views: 109

Answers (3)

adeneo
adeneo

Reputation: 318302

If the element is dynamic you'll need to delegate the event to an element that actually exists when binding the keydown :

$(document).on("keydown", "#existing_Flavours", function(event){
   switch(event.which){
      case 9:
           //tab called permit
          break;
      default:
           //event.preventDefault();
           //event.stopPropagation();
           // or just use return false
           return false;
    }
});​

Upvotes: 2

jodarove
jodarove

Reputation: 130

well, first of all, i dont like the switch to much (probably this has nothing to do), try:

$("#existing_Flavours").live("keydown", function(event){
    var keyCode = event.keyCode || event.which; 

    if (keyCode != 9) { 
      event.preventDefault(); 
    }

});

Upvotes: -1

idrumgood
idrumgood

Reputation: 4934

My guess is it has to do with which events actually cause a character to appear. I would try binding to keydown keyup keypress to make sure you catch all of them.

Upvotes: 0

Related Questions