Reputation: 4644
I am learning javascript and in a form validation example I found this : To check for required field
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
I have two questions :
In what case the input value could be null (x==null) and in what case input value is empty (x == "") ?
Why is return being used ? Is it necessary ? Is there a case where we return true ?
Upvotes: 1
Views: 125
Reputation: 15490
In what case the input value could be null (x==null) and in what case input value is empty (x == "") ?
null
means the name doesn't have any reference of any object. where ""
means an empty string.
in your case you will get null
if there is no element. and ""
when its value is empty string.
Why is return being used ? Is it necessary ? Is there a case where we return true ?
mostly return false is used to to stop the proccessing, if return is false we will no go further
go to this link for example
http://www.codeproject.com/Tips/404274/Client-Side-Validation-using-JavaScript
Upvotes: 2
Reputation: 1807
I'd add to @lol answer that the return false;
used here is probably used inside some event, like onSubmit
for the <form>
element in your HTML, this will ensure that the form isn't submitted. In general return false;
will tell the browser not to continue with the default behavior such as submitting a form, or navigating to a page, etc.
Upvotes: 2