Search code examples
javascriptjqueryhtmlformstwitter-bootstrap

Why does the bootstrap form validation happen after the submit button is pressed?


I have a form, built with bootstrap, and i have found that the form validation does not run before the submit button's onclick event, which is kind of useless.

Please see this fiddle for examples - press the register buttons on the 2 forms to see what i mean.

http://jsfiddle.net/5tr34k/ax13nLof/

I would like a way to prevent the onclick event happening until the form validation has passed successfully, then run the onclick javascript

<h3>Example</h3>
<form action="" method="post" name="registration_form1">
    <input type="text" class="form-control" placeholder="Username" required name="username" id="username">
    <input type="email" class="form-control" placeholder="Email" required="true" name="email" id="email">
    <input type="password" class="form-control" placeholder="Password" required name="password" id="password">
    <input type="password" class="form-control" placeholder="Confirm Password" required name="confirmpwd" id="confirmpwd">
    <button id="myButton2" onclick="alert('i happen before validation');" type="submit" class="btn btn-default" >Register</button>
</form>

In the above code, the javascript alert runs before the form is validated. Can this be prevented or changed so that the javascript runs after the form validation?


Solution

  • You need to use the submit event of the form, not the click event of the button

    $('#form').on('submit', function (e) {
        //your awesome code here
        alert('I HAPPEN BEFORE FORM VALIDATION');
    })
    

    Demo: Fiddle