0

I tried to do a simple validation on a button, but when I click the button without entering anything it still goes to testValidation1.html instead of popping up the alert window.

<html>

<head>
</head>

<body>

      <form action="testValidation1.html">

         Parameter1 : 
          <input type = 'text' name = 'param1'/><br>

          <input type='submit' value = 'submit' onclick = 'return validateForm()'>
      </form>

      <script type="text/javascript">

      function validateForm() {
             var f1 = document.forms[0];
             var p1 = f1.param1;

             if(p1.value.length == 0) {

                alert('Plz enter parameters');
                p1.focus();
                return false;
             }  
     }

      </script>


</body>
</html>
6
  • 2
    I might be dumb, but should it perhaps be onclick = 'validateForm()' instead of onclick = 'return validateForm()'? Commented Nov 20, 2014 at 21:09
  • 1
    Try onsubmit instead (within <form> tag). Commented Nov 20, 2014 at 21:11
  • 1
    I test it in my localhost .. it works fine .. it always show the popup .. Commented Nov 20, 2014 at 21:12
  • @IbrahimAsad, sometimes it shows the alert window but as soon as I clicked ok button it redirects me to testValidate1 page which it shouldn't right. Commented Nov 20, 2014 at 21:19
  • It should Never redirect to the other page ... I test it with IE,chrome , Firefox .. and every time it show the popup to me . :) Commented Nov 20, 2014 at 21:22

1 Answer 1

2

you might find it easier to use the submit event of the form to validate

function validateForm(event) {
    var form = this;
    var p1 = form.elements['param1'];
    if(p1.value.length === 0) {
        alert('Plz enter parameters');
        p1.focus();
        event.preventDefault();
        return false;
    }
}

document.getElementById('form').addEventListener('submit', validateForm);

http://jsfiddle.net/7j0usuam/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.