stack
stack

Reputation: 10228

How to detect whether switch() matches one of its cases?

I have a code like this:

$("textarea").on('keydown', function(e){
    if(e.ctrlKey){     // Ctrl is pressed
        switch (e.which) {
            case 66: // "B" button on the keyboard
                alert("it is bold"); 
                break;

            case 73: // "I" button on the keyboard
                alert("it is italic"); 
                break;
        }
        e.preventDefault();
        return false;
    }
});

The above code handles Ctrl + B and Ctrl + I on keydown of textarea. Also there is two lines of code which stop every things:

e.preventDefault();
return false;

This ^ codes stops the action of any button. For example Ctrl + S is deactivate now ..! What I need is to define if that switch() function matches a case, then run those two lines, else don't run those two lines. How can I do that?

Upvotes: 1

Views: 38

Answers (2)

Amit Ramoliya
Amit Ramoliya

Reputation: 392

Try like this if key press other then Ctrl+B or Ctrl+I then it won't do anything.

 $("textarea").on('keydown', function(e){
                if(e.ctrlKey){     // Ctrl is pressed
                   var codes= [66,73];
                   var a = codes.indexOf(e.which);
                   if(a > 0){
                    return false;
                  }else{
                   // your stuff
                   }                     
                }
            });

Upvotes: 3

Bergi
Bergi

Reputation: 664970

Use the default case!

switch (e.which) {
    case 66: // "B" button on the keyboard
        alert("it is bold"); 
        break;
    case 73: // "I" button on the keyboard
        alert("it is italic"); 
        break;

    default: // everything else
        return; // without preventing the default action
}
e.preventDefault();
return false;

Upvotes: 2

Related Questions