Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On submit form, return false not working

When I submit the form I got an alert message. When I accept the alert it will submit the form anyway. Returning false is ignored. Onclick can not be used. I try with var x = document.forms["form"]["fname"].value; and still same.

<form id="f" method="post" name="form" onsubmit="return validateForm();" action="#">
    <input type="text" name="fname" id="test" />
    <input type="submit" value="submit"/>
</form>
<script type="text/javascript">
        function validateForm() {
            var x = document.getElementById('test').value;
            if (x == null || x == 0 || x == "0") {
                alert("Stop");
                return false;
            }
        }
    </script>
like image 794
Nejc Galof Avatar asked Aug 28 '13 05:08

Nejc Galof


People also ask

What is return false in form submit?

return false stops a form from being submitted. For example the following form will not be submitted: <FORM> <INPUT TYPE="BUTTON" VALUE="Click Me"> </FORM> However the following form will: <FORM> <INPUT TYPE="SUBMIT" VALUE="Click Me"> </FORM>

How do I stop form submit when onclick event return false?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.

What happens if a function returns false?

If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onclick handler. Save this answer.

What is the reason for using a return false statement?

Web Developers use 'return false' in different ways. During form submission, if a particular entry is unfilled, return false is used to prevent the submission of the form.


1 Answers

Instead of <input type="submit" value="submit"/> use <input type="button" value="Submit" onclick='validateForm()'/>.

In your JS:

<script type="text/javascript">
    function validateForm() {
        var x = document.getElementById('test').value;
        if (x == null || x == 0 || x == "0") {
            alert("Stop");
        }
        else
            document.form.submit();
    }
</script>
like image 177
Aashray Avatar answered Sep 24 '22 17:09

Aashray