How to check if a username is taken, by checking against a JavaScript array. - Stack Overflow

var y=document.forms["form"]["user"].valueif (y==null || y=="" ){alert(&q

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 pare 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 ?

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 pare 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 ?

Share Improve this question asked Dec 2, 2011 at 13:32 Rudiger KiddRudiger Kidd 4961 gold badge6 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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;
}

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");
 }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745543471a4632233.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信