I'm trying to use the following switch statement in an ajax success callback:
success: function(datain) {
switch (datain)
{
case "ERROR. No ID. Try again":
$(".errors").append('There was an error.');
break;
case "ERROR. Wrong captcha. Try again":
$(".errors").append('There was an error.');
break;
}
}
datain is a string (typeof datain
returns string
) and it does indeed contain the same text, capitalization and punctuation as the case so why would it not match either of the cases?
console.log(datain)
and console.log("ERROR. No ID. Try again")
match exactly and both return a typeof
of string
so why does my case never get matched?
Solution and cause
The solution is offered by palswim below $.trim(datain)
. The cause was visible in Firebug and it was the fact that the string had a newline at the end while my switch case did not... so I was getting "foo\n" and trying to match "foo". Given that js uses ===
in the switch this, naturally (now that I see it), is why it failed.