Kombuwa
Kombuwa

Reputation: 1651

Intercept a form submit and prevent or allow submission

In my mvc app I have a form that needs to prevent submit from default and resubmit if it’s acceding to my conditions. Even though it give me my alter message form is not resubmiting.

$("form").submit(function (e) {
    e.preventDefault();
    var myform = this;
    var id = $("#itemID").val();
    var brand = $("#brand").val();
    var qty = $('[name=qty]').val();

    $.get("http://192.168.192.106/data/" + id + "?brand=" + brand, function (data, status) {
        var diff = data - qty;
        if ((data - qty) > 0) {
            myform.submit();
        } else {
            alert("Qty is Grater than Stock");
        }
    });
});

Upvotes: 1

Views: 155

Answers (2)

A J
A J

Reputation: 4024

There are two solutions:

First In your code, you have added a e.preventDefault() at start that will stop form from being submitted. If all inputs accedes your conditions, you can send these inputs to another page through AJAX.

Second
You can add e.preventDefault() wherever condition fails.

Upvotes: 0

Avinash Jain
Avinash Jain

Reputation: 7616

The first line e.preventDefault(); stop your submission process. You should use e.preventDefault(); inside else condition, to make sure submission stop only when validation fail.

Upvotes: 2

Related Questions