var y=document.forms["form"]["user"].value
if (y==null || y=="" )
{
alert("Username cannot be Blank");
return false;
};
var x = new Array();
x[0] = "bill";
x[1] = "ted";
x[2] = "jim";
for ( keyVar in x )
{
if (x==y)
{
alert("Username Taken");
return false;
};
};
How do I compare a variable to that in a JavaScript array, I managed to make the example above, but the second part, the bit I need, doesn't work. any ideas ?
You can simply check an array with the Array.prototype.indexOf
method.
var x = [ 'bill', 'ted', 'jim' ],
y = 'ted';
if( x.indexOf( y ) > -1 ) {
alert('Username Taken');
return false;
}
You should use an object instead:
var y = document.forms["form"]["user"].value;
if (y == null || y == "") {
alert("Username cannot be Blank");
return false;
};
var x = {};
x["bill"] = true;
x["ted"] = true;
x["jim"] = true;
if (x[y] === true) {
alert("Username Taken");
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With