简体   繁体   中英

stop submission if form is not validated

I have a form and I have a "cancel" and submit button. when user submits the form, if required fields are not filled, I want to alert("error") and stop the form to be submitted.

here is my simple jquery code but when user click ok button on alert box, it continues to submit.

<script>
$(document).ready(function () {
    $('#<%=btn_reddet.ClientID %>').click(function (event) {
        alert("Error!");
        event.preventDefault();
    });
});
</script>

how can I make it stop submitting after alert?

instead of .click , you can use .submit , You just need to return false to stop form submission

$('#formID').on('submit',function (event) {
        alert("Error!");
        return false;
});

Use the $('form').submit() event instead of $('submit_button').click() . Then return false if validation fails:

$(document).on('submit','form',function(e) {
    var validated = true; 
    // some validation code which sets 'validated = false' if it fails
    return validated;
});

If you want to use

event.preventDefault();

Then I believe that also needs to be followed by

event.stopPropagation();

Otherwise you can just use return false.

event.preventDefault() and return false do not work the same, the differences exist when something goes wrong (read: error) and whether or not event.preventDefault() has already executed or not, here is an example of when it matters and why return false does not always work:

$('a').click( function(e){
    $(this).css("background", "green");
    err();  // err is not defined, so JavaScript will throw error, and the browser will ignore rest of the code (return false;). The browser will perform the default action.
    return false;
});
$('a').click( function(e){
    e.preventDefault();
    $(this).css("background", "green");
    err();  // err is not defined, so JavaScript will throw error, and the browser will ignore rest of the code. We already called event.preventDefault() so the browser will not perform default action.
});

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