Reputation: 496
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 ?
Upvotes: 4
Views: 859
Reputation: 189
You can do this quite simply with jQuery
The list of the array values
var x = new Array();
x[0] = "bill";
x[1] = "ted";
x[2] = "jim";
then
if(jQuery.inArray("John", arr) == -1){
alert("Username Taken");
}
Upvotes: 3
Reputation: 236192
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;
}
Upvotes: 4
Reputation: 76910
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;
}
Upvotes: 3