Case-insensitive switch-case
Asked Answered
P

4

14

OK, so let's say I have this:

$(function() {
  $('#good_evening').keyup(function () {
    switch($(this).val()) {
    case 'Test':
      // DO STUFF HERE
      break;
    }
  });
});

... this would only run if you typed "Test" and not "test" or "TEST". How do I make it case-insensitive for JavaScript functions?

Percutaneous answered 11/9, 2010 at 7:29 Comment(2)
possible duplicate of How do I use jQuery to ignore case when selecting?Ballot
@Lazarus: This is asking about case-sensitivity for switch-case, not jQuery selectors (as the other question is). It isn't a duplicate.Nexus
L
45
switch($(this).val().toLowerCase()) {
    case 'test':
    // DO STUFF HERE          
    break;
}
Labrecque answered 11/9, 2010 at 7:31 Comment(3)
Ah yes -- brilliant yet simple solution. Thanks.Percutaneous
2mins faster than me. slaps self for editing tags before answering the question :)Oyer
@dan: glad to have helped :) @Marko: can't count the amount of times I've deleted an answer and up voted someone else ;-)Labrecque
L
6

Convert it to upper case. I believe this is how it is done, correct me if I am wrong... (dont -1 me =D )

$(function() {
    $('#good_evening').keyup(function () {
            switch($(this).val().toUpperCase()) {
            case 'TEST':
            // DO STUFF HERE
            break;
        }
    });
});
Lucianolucias answered 11/9, 2010 at 7:33 Comment(1)
Correct! But Matt was first. Sorry. :PPercutaneous
O
4

Why not lowercase the value, and check against lowercase inside your switch statement?

$(function() {
    $('#good_evening').keyup(function () {
        switch($(this).val().toLowerCase()) {
        case 'test':
        // DO STUFF HERE
        break;
        }
    });
});
Oyer answered 11/9, 2010 at 7:33 Comment(0)
C
0

Make sure val() is a String if it could be null switch(String($(this).val()).toLowerCase()) {

Caz answered 25/4, 2023 at 17:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.