7

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>
11

2 Answers 2

9

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>
4
  • The question says onclick cannot be used.
    – mechenbier
    Commented Aug 28, 2013 at 5:33
  • The question would be why not use onclick and onclick of what.
    – Aashray
    Commented Aug 28, 2013 at 5:34
  • Onclick on button is ok. On form is problem because I have 4 buttons.
    – Nejc Galof
    Commented Aug 28, 2013 at 5:39
  • @NejcGalof, please ask different questions for different subjects
    – Sergio
    Commented Aug 28, 2013 at 6:08
0

Give this script inside of head tag and check it.

<script type="text/javascript">
        function validateForm() {
            var x = document.getElementById('test').value;
            if (x == null || x == 0 || x == "0") {
                alert("Stop");
                return false;
            }
        }
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.