return value in javascript
I am new to javascript and I am little bit confused about the syntax.
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
My question is If I write开发者_如何学运维 onsubmit="return validateForm()" or write onsubmit="validateForm()". What's the difference between these two syntax. So I submitted before just an example.
Here it is example
Event = function(); or Event = return function();
What's the difference between these two syntax
They're both invalid.
The return
statement should be used within a function. The expression following a return
statement is what will be returned from the function, so:
function foo() {
return 1234;
}
foo(); // => 1234
If you want to assign a function to the Event
identifier, then you would do it like so:
Event = function() {
// function body (what do you want the function to do?)
};
onsubmit="validateForm()"
just calls the function and whatever is returned is lost and does not effect anything.
But in onsubmit="return validateForm()"
the returned value is returned again and if false will not submit the form and if true will continue the submitting process.
So you can use it like:
function check()
{
if(document.getElementByName("fname").value == ""){
return(false); //Do not submit the form
}
return(true); //Submit the forum
}
<form name="myForm" action="demo_form.asp" onsubmit="return(check());" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
精彩评论