How to check if a username is taken by checking for a JavaScript array.

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 to compare a variable with a JavaScript array, I managed to make an example above, but the second part - the bit that I need, does not work. any ideas?

+4
source share
3 answers

Instead, you should use an object:

 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; } 
+3
source

You can simply check the array using the Array.prototype.indexOf method.

 var x = [ 'bill', 'ted', 'jim' ], y = 'ted'; if( x.indexOf( y ) > -1 ) { alert('Username Taken'); return false; } 
+4
source

You can do it quite simply with jQuery

List of 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"); } 
+3
source

Source: https://habr.com/ru/post/1384325/


All Articles