Click here to Skip to main content
16,019,614 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

What I have tried:

Explain the second line please and why we need to use return false?
Posted
Updated 1-May-17 20:40pm
v2
Comments
Debarshi Chakraborty 2-May-17 2:39am    
that's the name of the control. fname stands for 'first name'. (guessed it from the error message). you need to check from where this function is called. the 'false' can be used either to stay on the form or perform some other activities (some rollback or so)

1 solution

document.forms will return a collection of all of the forms within a page.
So document.forms["myForm"] will return the form with the name "myForm" from that collection.
And document.forms["myForm"]["myElement"] will return an element of that form - a control for example.
So document.forms["myForm"]["myElement"].value will return the current data in that control.
I.e. in your case
JavaScript
var x = document.forms["myForm"]["fname"].value;
Gets what the user typed in the control fname and stores in in a variable called x

This is a validation function: it's purpose is to tell the outside world if what the user typed was acceptable. If it isn't, it returns false to indicate that.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900