Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot return from outside a function or method?

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?

like image 397
Nishit Jain Avatar asked Jan 19 '12 10:01

Nishit Jain


1 Answers

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.

  1. 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;
    
  2. 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.

like image 121
BalusC Avatar answered Sep 28 '22 10:09

BalusC