简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM