Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

charAt() comparison

Status
Not open for further replies.

Icemann

Programmer
Feb 19, 2001
2
US
I'm using JavaScript to validate information on a form prior to submission and I've run into a snag. One field on the form is for an order number which must begin with the letter 'n' (either upper or lower case). I'm using the following code to check for the leading 'n' using onSubmit to access the function:
if(document.forms[0].ord_nbr.value.charAt(0) != n) {
alert("......");
return false;
}
I've tried surrounding the 'n' on the right side of the comparison with single quotes, double quotes, parenthesis and nothing seems to work. I know there must be a simple solution to this.

Using another alert, I can see that the charAt() method is catching the correct value for the first character in the field.

Thanks, JS newbie
 
Hi Icemann!
You didn't write the rest of your code, maybe the problem is there.
Anyway, here is a code that I checked just now:

<script>
function check() {
if (document.forms[0].ord_nbr.value.charAt(0) != &quot;n&quot;)
{
alert(&quot;error in input!&quot;);
return false;
}
else alert(&quot;OK&quot;);
}
</script>
</head>
<body>

<form>
<input type=text name=ord_nbr>
<input type=submit onclick=&quot;check()&quot;>
</form>

It works. 'N' should be with single or double quotes.

Enjoy!

Andrew | starway@mail.com
 
Andrew,

You were absolutely right. I had my blinders on trying to figure out why I couldn't compare the strings. I was actually validating for three possibilities in the if statement and I had an || where I needed an &&.

Thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top