View Full Version : checking the text in a textbox against a JavaScript array

11-09-2010, 05:05 PM

Can you someone point me to the right script?

I have a text box and would like to see if the value of the input matches the values defined in a JavaScript array.

For example, the JavaScript array will hold five values:

v1 = Tom
v2 = Jerry
v3 = Michael
v4 = Stephanie
v5 = Michelle

If the text box does not equal one of those values, an alert will pop up stating it does not match.


11-09-2010, 05:25 PM
Well, this is not all js, but i think it's useful.
You could use a form with select, here's the example:
this is html

<form name="nameform">
<select name="nameselect">
<option selected value="">Choose a value</option>
<option value=1>Tom</option>
<option value=2>Jerry</option>
<option value=3>Michael</option>
<input type="submit" value="Submit Value" onClick="getValue(this.form)">

than you can access value from js with:
and this is js

function getValue(form){
var value=form.nameselect.value;
return value;

you could also create the select value with js of your array:

<select name="nameselect">
<script language="JavaScript">
var myArray= newArray ("Tom", "Jerry", "Michael");
document.write("<option value=\""+myArray[i]+"\">"+myArray[i]+"</option>");

my 2 cents

Philip M
11-09-2010, 05:34 PM
Try this:-

<script type = "text/javascript">

function chkName() {

var v = [];
v[1] = "Tom"; // names must be in quotes
v[2] = "Jerry";
v[3] = "Michael";
v[4] = "Stephanie";
v[5] = "Michelle";

var str = document.getElementById("username").value;
str = str.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
str = str.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()}); // reformat to lower-case with initial capital

var match = false;
for (var i =0; i<v.length; i++) {
if (str == v[i]) {
match = true;

if (!match) {
alert ("The name " + str + " does not match our list!");
document.getElementById("username").value = "";
return false;
else {
alert ("Hello " + str + "!");


I think that the weakness of the select list is that the valid names are visible to the user. But of course the user can simply see the names list with view source so the security either way is zero.

He thought he saw a Argument
That proved he was the Pope:
He looked again, and found it was
A Bar of Mottled Soap.
"A fact so dread," he faintly said,
"Extinguishes all hope!"

- Lewis Carroll