var data = "needactivation:9";
if (data.indexOf(":") == true) {
replyData = data.split(":");
if (replyData[0] == "needactivation") {
alert("User Id Is " + replyData[1]);
}
}
else if (data == "success") {
window.location.href = "/";
}
else {
alert("Unknown error.");
}
Is my JavaScript. It should alert the User ID but it gives a unknown Error. Any idea whats wrong with this script?
Not sure if this part matters, but i'm using the latest jQuery on the page also.
var data = "needactivation:9";
if (data.indexOf(":") == true) {
replyData = data.split(":");
if (replyData[0] == "needactivation") {
alert("User Id Is " + replyData[1]);
}
}
else if (data == "success") {
window.location.href = "/";
}
else {
alert("Unknown error.");
}
Is my JavaScript. It should alert the User ID but it gives a unknown Error. Any idea whats wrong with this script?
Not sure if this part matters, but i'm using the latest jQuery on the page also.
Share Improve this question asked May 1, 2011 at 23:23 KeverwKeverw 3,7867 gold badges33 silver badges55 bronze badges5 Answers
Reset to default 5indexOf
returns an index (or -1
if not found), not a boolean. Change this:
if (data.indexOf(":") == true) {
To this:
if (data.indexOf(":") !== -1) {
Alternatively, you could split
regardless and then check replyData.length
.
String.indexOf()
returns a number >= 0 when the string is found, not a boolean true
value
Your test should read:
if (data.indexOf(":") >= 0) {
...
}
var data = "needactivation:9";
if (data.indexOf(":") >= 0) {
replyData = data.split(":");
if (replyData[0] == "needactivation") {
alert("User Id Is " + replyData[1]);
}
}
else if (data == "success") {
window.location.href = "/";
}
else {
alert("Unknown error.");
}
Try if (data.indexOf(":") != -1) {
In addition to verifying that the above answers are correct, I just wanted to say that you may also want to employ some kind of try/catch logic once you've changed your true
to -1
since a string like Anything:
will have an indexOf(":") >= 0
but will split in such a way that your reference to replyData[1]
will throw yet another error.