While developing a web application I want to perform certain validation check and only after sucesssful validation I need to post the form and redirect control to next page.
JavaScript code:
function fnCheckEmptyField()
{
var strDomain = document.getElementsByName("txtIIDN").value;
if (strDomain == null)
{
document.getElementById("lblValidityStatus").innerHTML = "";
document.getElementById("lblValidityStatus").innerHTML = "Domain Name Field Can't be Left Blank";
return false;
}
else
{
return true;
}
}
Relevant HTML code:
<form action="Result.jsp" name="validityCheck" onsubmit="return fnCheckEmptyField()">
<input type="text" id="txtIIDN"/>
<input type="submit" id="btnValidityCheck" value="Check Validity" />
</form>
The line onsubmit="return fnCheckEmptyField()"
shows an error Cannot return from outside a function or method and after execution of the JavaScript function form is getting submitted regardless the text field is blank or not.
I have placed alerts inside if
condition and it is sure that if field is empty function returns false
.
I don't know what's wrong with my code and why this errors with Cannot return from outside a function or method.
What's the cause and how can I solve it?
the line
onsubmit="return fnCheckEmptyField()"
showing an error Cannot return from outside a function or method
That's specific to Eclipse. Eclipse is wrong here, that line is perfectly fine. Just ignore the Eclipse error. If you want, you can always disable its JS validation.
and after execution of the java script function form is getting submitted regardless the text field is blank or not.
That's because your JavaScript function is wrong. You've 2 mistakes in your JS code.
The getElementsByName()
call is incorrect.
var strDomain = document.getElementsByName("txtIIDN").value;
To retrieve an element by ID, you need getElementById()
.
var strDomain = document.getElementById("txtIIDN").value;
Empty values are not null
, but just empty string.
if (strDomain == null)
You need to check its length instead.
if (strDomain.length == 0)
Or just make use of JS boolean magic.
if (!strDomain)
By the way, the line document.getElementById("lblValidityStatus").innerHTML = "";
is unnecessary in this code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With