homepage Welcome to WebmasterWorld Guest from 54.242.126.9
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

This 31 message thread spans 2 pages: < < 31 ( 1 [2]     
JavaScript JumpStart #2 - form validation
part 2
korkus2000

WebmasterWorld Senior Member korkus2000 us a WebmasterWorld Top Contributor of All Time 10+ Year Member



 
Msg#: 437 posted 12:31 pm on Jun 9, 2003 (gmt 0)

JavaScript JumpStart - Part 2
Form Validation - Part 2

In the last JavaScript JumpStart [webmasterworld.com] we talked about the basics of JavaScript form validation. Now we can look at how to combine these basics to create validation for any form you may have.

Form Object
Before we start lets take a look at the form object. The form object has 2 event handlers; onSubmit and onReset. We covered the onSubmit in the last JumpStart. The onReset is similar, firing off when the form is reset, but you don't need to return a value. onReset is not used much, but can come in handy if you need to process information if the form is reset.

The form object also has methods to fire off these actions; submit() and reset(). Calling these methods will reset the form or submit it.

document.form1.submit(); = submits the form
document.form1.reset(); = resets the form

These can become handy if you want to execute form actions from another page or frame.

Form Elements
First lets look at the different form elements and how they are accessed. You can copy and paste this code into an HTML page, and have it function. Here is a basic form with all the form elements:

<form name="form1">
<input type="text" name="textbox1" value="textbox1" onBlur="alert(document.form1.textbox1.value)"><br>
<input type="hidden" name="hidden1" value="hidden1"><br>
<textarea cols="10" rows="5" name="textarea1" onBlur="alert(document.form1.textarea1.value)">textarea1</textarea><br>
<input type="password" name="password1" value="password1" onBlur="alert(document.form1.password1.value)"><br>
<input type="radio" name="radio1" value="radio11" onclick="alert(document.form1.radio1[ 0 ].checked)">
<input type="radio" name="radio1" value="radio12" onclick="alert(document.form1.radio1[ 1 ].checked)">
<input type="radio" name="radio1" value="radio13" onclick="alert(document.form1.radio1[ 2 ].checked)"><br>
<input type="checkbox" name="checkbox1" value="checkbox1" onClick="alert(document.form1.checkbox1.checked)"><br>
<select name="select1" onchange="alert(document.form1.select1.options[document.form1.select1.selectedIndex].value)">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select><br>
<input type="button" name="button1" value="button1" onClick="alert(document.form1.button1.value)"><br>
<input type="submit" name="submit1" value="submit1" onClick="alert(document.form1.hidden1.value)"><br>
</form>

I have added alerts to each element using the corresponding event handler for that element.

Textbox
We have talked about the text box in the last JumpStart, but lets look at it again.

<input type="text" name="textbox1" value="textbox1" onBlur="alert(document.form1.textbox1.value)">

I have used the onBlur event handler to fire off the alert. When you click inside of a text box it gives it focus. When you click out of it after giving it focus, you blur the textbox. So when we blur the text box it will fire off the alert. In the alert we have the road map to the text box’s value. So when the text box gets blurred it will alert its value.

Textarea

<textarea cols="10" rows="5" name="textarea1" onBlur="alert(document.form1.textarea1.value)">textarea1</textarea>

We have the same thing for the text area.

Password

<input type="password" name="password1" value="password1" onBlur="alert(document.form1.password1.value)">

Again, the same for the password field.

I will mention that you can get the default value for the text area, password and text box by replacing the value in our example with defaultValue:

document.form1.textarea1.defaultValue

You can also get the name and type of the text area, password and text box like this:

document.form1.textarea1.name = the value in the name attribute
document.form1.textarea1.type = the value in the type attribute

Radio Buttons
Radio buttons are a little different. Radio buttons have a click event. So I used their onClick event handler.

<input type="radio" name="radio1" value="radio11" onclick="alert(document.form1.radio1[ 0 ].checked)">
<input type="radio" name="radio1" value="radio12" onclick="alert(document.form1.radio1[ 1 ].checked)">
<input type="radio" name="radio1" value="radio13" onclick="alert(document.form1.radio1[ 2 ].checked)">

We have two things to check with radio buttons the checked property and value property. We need to find out which radio button is checked then find out that buttons value. To do this we need to write a small function that will check the buttons and see which one has been checked. Then we will get its value. So lets look at a function to handle this:

<script language="JavaScript" type="text/javascript">
function whichButton(){
var clickedButton = "";
for(i=0;i<3;i++){
if(document.form1.radio1[ i ].checked == true){
clickedButton = document.form1.radio1[ i ].value;
}
}
alert(clickedButton);
}
</script>

So lets take this one line at a time. First it is nested in script tags to let the browser know that it is javascript code. Next we declare the function using the “function” keyword and the name of the function. Functions are incased in curly brackets so we open and close with curly brackets.

var clickedButton = "";

Here we are declaring a variable and assigning it the value of nothing. When you want to use a variable you should declare it using the “var” keyword. You do not have to assign it, but I did to show you how you can declare and assign variables on the same line. We close with the JavaScript end of line character the semicolon.

So now we have a variable we can use in the function “clickedButton” with basically no value. JavaScript is case sensitive so if we called clickedbutton later on, JavaScript wouldn’t know what to do with it. It must have the capital B to be the variable we just declared.

for(i=0;i<3;i++){

for loop
In the last JumpStart we talked about the if and if…else statements. Now lets look at loops. The most common is the for loop. Loops iterate through a code block. for loops iterate through a code block a certain number of times. The loop starts out with the for keyword. Then open parenthesis.

i=0;

Here we are assigning the variable i the value of 0 and using a semicolon to tell JavaScript that we are done with this statement. We did not declare i with the var keyword, and don't have to. You could if you wanted like this:

for(var i=0;i<3;i++){

JavaScript starts with the number 0. When you are counting in JavaScript remember to always start at 0 and not 1. Since we had 3 radio buttons we need the loop to go 3 times.

i<3;

So we tell the loop that we want it to process the loop until i equals 3. So it will start at 0 and end at 2. It will not run once i = 3 since we told it to only run if i < 3. Again we tell it that we are done with this command with a semicolon.

i++){

++ is to auto increment i. It is equal to i = i + 1. So every time the loop runs i will have 1 added to it until it reaches 3. Since the ++ is after i, it will increment by one after the loop. If it were before the i it would increment before the loop. There is also -- which is the auto decrement. Then we close the expression with a close parenthesis. And open a bracket to contain the code block we will loop through.

if(document.form1.radio1[ i ].checked == true){
clickedButton = document.form1.radio1[ i ].value;
}

Now we have an if statement that tests each radio button to see if it is checked. JavaScript puts every element on the page in an array. An array is a variable that can hold many values. You specify which value you want by putting the number of the item located in the array. So to access the first radio button or radio11 we call the radio button name radio1 then the number of the position the first button is in the array. Since it is the first radio button we want, we would call radio1[ 0 ]. Why radio1[ 0 ]? Because JavaScript starts at 0 and not 1.

if(document.form1.radio1[ i ].checked == true){

So the first go around the loop radio1[ i ] = radio1[ 0 ] because i=0. After the loop runs once it auto increments i and i becomes 2 making it radio1. Next it increments and i becomes 2. Then as it finishes that it will end because i will not be less than 3.

So we are trying to find which button is checked. A checked button will have a checked property == true. Remember we use == to see if the 2 values are the same and = to assign a new value.

clickedButton = document.form1.radio1[ i ].value;

Once the if statement gets a radio button that == true it will fire off its code block. This code block is assigning the value of the checked radio button to the variable clickedButton. Then we close the if statement with a close curly bracket. Then close the for loop with a close curly bracket.

alert(clickedButton);
}

We then alert the value of the variable to see that it is working. We place the alert outside of the curly brackets for both the loop or we would have three alert boxes to close. Then we close the function. We will not be using the value for what we are doing here, but I thought it would be a good chance to see how you would do it. For this we only want to make sure that a radio button has been clicked.

Checkbox

<input type="checkbox" name="checkbox1" value="checkbox1" onClick="alert(document.form1.checkbox1.checked)">

Checkboxes are like radio buttons since they are either on or off. They are just not tied to other checkboxes. With checkboxes you want to check to see if it is checked. Checkboxes and radio buttons have the checked, defaultChecked, name, type and value properties. Radio buttons also have the length property.

Select Box

<select name="select1" onchange="alert(document.form1.select1.options[document.form1.select1.selectedIndex].value)">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

Select boxes are very common elements in forms. Like radio buttons they have multiple options. These options are kept in an array. JavaScript has given us a nifty way of accessing the value that is selected. We use the select’s options array. Inside the array we give the JavaScript a road map to the select we want, and ask for its selectedIndex property.

document.form1.select1.options[document.form1.select1.selectedIndex].value

This line gives us the current value of the select element. We can also get the text property this way.

Buttons and Submit Buttons

<input type="button" name="button1" value="button1" onClick="alert(document.form1.button1.value)">

Buttons and submits are basically the same thing in JavaScript. Submits do submit the form, but all properties of a button will work on a submit. Usually we don’t want to access the elements, but we can if needed. You can find the value, name, and type.

Hidden Fields

<input type="hidden" name="hidden1" value="hidden1">
<input type="submit" name="submit1" value="submit1" onClick="alert(document.form1.hidden1.value)">

Hidden fields are hidden so they are not accessible by their own events. We need to trigger an event to access the hidden element, so I used a submit button. You can access the type, name, and value of a hidden field.

JavaScript Comments
JavaScript also has comment characters. It is //. Anything after a // will not be read or parsed by JavaScript. The problem with that is URLs have http://. These will start a comment. The way around that is to escape these characters. You do this with a \. So to stop a comment with http://www.webmasterworld.com would be to add the \ in between the // like this http:/\/www.webmwsterworld.com. JavaScript will know that \/ is really /.

Validation Function
So lets look at making sure our original form has all of the fields filled out. We will write a function that tests each field and will alert the user of all fields not needed. We will be removing the hidden field and the button since users cannot fill these elements out. So here is our new form with an onsubmit event handler calling our validation function. We have also added a dummy option in the select box with no value. This will let us know if nothing has been selected.

<form action="" name="form1" onsubmit="return checkFields()">
<input type="text" name="textbox1"><br>
<textarea cols="10" rows="5" name="textarea1"></textarea><br>
<input type="password" name="password1"><br>
<input type="radio" name="radio1" value="radio11">
<input type="radio" name="radio1" value="radio12">
<input type="radio" name="radio1" value="radio13"><br>
<input type="checkbox" name="checkbox1" value="checkbox1"><br>
<select name="select1"">
<option value="">Make a Selection</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select><br>
<input type="submit" name="submit1" value="submit1"><br>
</form>

Now we need a checkFields function to validate the form. I will use comments for commentary for the sake of space.

<script language="JavaScript">
function checkFields() {
emptyfields = "";
if (document.form1.textbox1.value == "") {
emptyfields += "\n - Textbox1";
}
if(document.form1.textarea1.value == "") {
emptyfields += "\n - Textarea1";
}
if (document.form1.password1.value == "") {
emptyfields += "\n - Password1";
}
var clickedButton = "";
for(i=0;i<3;i++){
if(document.form1.radio1[ i ].checked == true){
clickedButton = "true";
break
}
}
if (clickedButton == "") {
emptyfields += "\n - Radio1";
}
if (document.form1.checkbox1.checked == false) {
emptyfields += "\n - Checkbox1";
}
if (document.form1.select1.options[document.form1.select1.selectedIndex].value == "") {
emptyfields += "\n - Select1";
}


if (emptyfields!= "") {
emptyfields = "These fields are required:\n" +
emptyfields + "\n\nPlease fill in all required feilds";
alert(emptyfields);
return false;
}
else return true;
}
</script>

So lets take a look at this function.

//First we declare the checkFields function with the function keyword.
function checkFields() {
//We declare an emptyfields variable and set its value to “”.
emptyfields = "";
//We use an if statement to see if the textbox has a value entered or not.
//Without a value attribute text fields have a value of “” in JavaScript.
if (document.form1.textbox1.value == "") {
//We will now assign a sting to our emptyfields variable.
//We use the += operator to add our string to the end of the current value
//and not write over the current value.
//It doesn’t matter the first time but later it will.
//We are using this variable to hold all of the fields not completed
//to alert the user which ones they missed.
//We add a little formatting to the string so it is more useable
//with spaces and a -.
//I will explain the \n later in the function.
emptyfields += "\n - Textbox1";
}

//Basically the same as the textbox
if(document.form1.textarea1.value == "") {
emptyfields += "\n - Textarea1";
}

//Basically the same as the textbox
if (document.form1.password1.value == "") {
emptyfields += "\n - Password1";
}

//With the radio button we need to loop through the buttons
//to see if any have been clicked.
//We declare our variable that will tell us if one has been clicked or not.
var clickedButton = "";
//Start our for loop.
for(i=0;i<3;i++){
//Check to see if the current button has been clicked.
if(document.form1.radio1[ i ].checked == true){
//If the current button in the loop has been clicked
//we set our variable to "true".
//It could be anything really, we just don’t want it equal to "".
clickedButton = "true";
//We use the break keyword to stop the loop since we found a button clicked.
break
}
}

//Now we use the clickedButton variable to test.
if (clickedButton == "") {
emptyfields += "\n - Radio1";
}

//Since this is a checkbox we check to see if the checked property is true or false.
if (document.form1.checkbox1.checked == false) {
emptyfields += "\n - Checkbox1";
}

//Since we created a dummy option with the value of "",
//we look to see if that is still the value.
if (document.form1.select1.options[document.form1.select1.selectedIndex].value == "") {
emptyfields += "\n - Select1";
}

//Now we have check all of our fields
//We need to alert the user, which required fields they missed
//so they can complete the form.
//We check to see if the emptyfields variable has anything in it.
//We use the!= operator or not equal to.
//We are saying if the emptyfields variable is not equal to the original value
//then do this code block.
if (emptyfields!= "") {
//If there is something other than the original value,
//we take our emptyfields variable and create a usable alert for our user.
//We want to combine all of these values into something
//users can use. We use the + operator on strings to concatenate them.
//Concatenation just means to tack strings together to make one big string.
//So we take the first value we want on the alert box.
//We follow this with \n. \n is the new line character in JavaScript.
//It makes the next string start on a new line like <br>
//would in HTML. Then the + to tack on the next string.
emptyfields = "These fields are required:\n" +
//Now we want to add the strings we built in the if statements above.
//Since JavaScript evaluates before assigning we will still have
//those earlier values before overwriting them.
//Then we add more instructions for our users.
//To make the alert box less cluttered I added 2 new line characters
//before the instructions.
emptyfields + "\n\nPlease fill in all required feilds";
//Then we alert the value.
alert(emptyfields);
//Now we tell the form not to submit by returning false.
return false;
}

//If emptyfields was the original value we return true
//to tell the form to continue submitting.
else return true;
}

The Alert
If you don’t fill out any fields the alert box should have this text:

These fields are required:

- Textbox1
- Textarea1
- Password1
- Radio1
- Checkbox1
- Select1

Please fill in all required fields

To me this is much more informative to the user and will help alleviate frustration filling out forms.

So that’s it. I have rambled on enough. Hopefully JavaScript is starting to make more sense.

[1][edited by: korkus2000 at 1:01 pm (utc) on June 9, 2003]

 

korkus2000

WebmasterWorld Senior Member korkus2000 us a WebmasterWorld Top Contributor of All Time 10+ Year Member



 
Msg#: 437 posted 3:50 pm on Jun 21, 2003 (gmt 0)

Great thanks ShawnR!

This 31 message thread spans 2 pages: < < 31 ( 1 [2]
Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved