Beginners Guide to JavaScript
(Part 3)
By Richie Lai
Forms Manipulation
Let's take this script a step further and verify the data (if a user enters a non-number, we're going to get a script error). And while we're at it, let's say that a user shouldn't be able to enter a number greater than 100 or less than 0. To do this, we're going to have to do some kind of verification to decide whether the INPUT is valid or not. So let's add this wrapper type function around our function. In addition, let's do some form manipulation too. Instead of an alert box, let's make it display the answer in our form. function AddNumber3(x,y) { answer=eval(x)+eval(y); return answer; } function CheckData(x,y) { answer=""; if(isNan(x) || isNan(y) || x =="" || y =="") alert("The values you entered are invalid."); else { if(x > 100 || x < 0 || Y > 100 || y < 0) alert("Values are outside of valid 0-100 limits"); else Answer=addnumber3(X,Y); } return answer; } Try entering invalid numbers and characters and see what happens. This script is pretty simple. Basically, we check to see if a number is valid with isNan(). if(isNan(x) || isNan(y)) We show appropriate message boxes for each error. The only thing we do is: <INPUT TYPE="button" onClick="this.form.Answer.value=CheckData(this.form.Value1.value,this.form.Value2.value)" value="Answer!"> Notice how we get the answer to the answer box. AddNumber3 returns the answer to CheckData, which then returns it to whatever is calling it. In this case, we say that this.form.Answer.value takes the value of whatever CheckData returns. As we follow the code, it is what AddNumber3 returns. And just like that, you can have the answer on screen. There are other types of form data that require verification, most notably valid phone numbers and email addresses. These are accomplished the same way--by writing a wrapper class. Methods are different (such as for email addresses where you have to check for an @ symbol), but JavaScript gives us functions to accomplish them. Let's take a quick look how. function CheckEmail(x) { if (x.indexOf("@",0) > 0 ) alert(x + " is a valid email"); else alert(x + " is not a valid email address"); } In this example we use the indexOf() function that returns the index of a specific character, in this case the @ symbol. Basically, we are checking to see if it returns an index; if it doesn't return a value greater than 0, we know it wasn't found. Piece of cake!
[ Click here to move to the next part of the article ]
This article first appeared April 11th, 1999.
Copyright © 1999-2000 internet.com Corp.
All Rights Reserved. Legal Notices.
Contact the WebDeveloper.com staff
Last modified:
Tue May 9 21:02:38 EDT 2000
|