Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript switch with multiple variables in case

This feels like a silly question but I can’t get it to work:

I am building an event handler that I want to trigger two different outcomes if the user presses "enter" or "shift Enter"

I have this code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


         switch(e){
            case (e.keyCode == 13 && !e.shiftKey):
                console.log("Enter")
                break;
            case (e.keyCode == 13 && e.shiftKey):
                console.log("Enter&Shift")
                break;
            default:
                console.log(`Sorry, we are out of it.`);
        }

but something is not working because it always go to default…despite the fact that e.keyValue is actually 13 and e.shiftKey is true…so I am passing the event correctly.

It’s the switch that is wrongly built.

>Solution :

You shouldn’t use a switch statement for this, but regular if and else statements.

if (e.keyCode == 13 && !e.shiftKey) {
    console.log("Enter");
} else if (e.keyCode == 13 && e.shiftKey) {
    console.log("Enter&Shift");
} else {
    console.log(`Sorry, we are out of it.`);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading