iJade
iJade

Reputation: 23791

prevent postback using jquery,javascript

Here is my HTML code

<form id="form1" runat="server">
    <input id="q" required />
    <input id="btn" type="submit" value="Search" />
</form>

I'm trying the HTML 5 required feature in asp.net. The above code works. But a post back also occurs. Is there a way to prevent the post back using JavaScript, jQuery or any other method? I tried to prevent the post back using jQuery

 $(document).ready(function () {
        $('#btn').click(function (evt) {
            evt.preventDefault();
        });
    });

But this makes the required validation not to fire.

Note: There are more than one button in the form.

Upvotes: 2

Views: 9899

Answers (2)

j7m
j7m

Reputation: 1075

Here is the updated JsFiddle which has two inputs (one is required) and two buttons (one is submit).

HTML:

<form id="form1" method="get" action="http://example.com">
<input id="q" required />
<input id="w"  />

<input id="btn" type="button" value="Cancel" />
<input id="btn" type="submit" value="Submit" />

Javascript

    $('#form1').on("submit", function (evt) {
    evt.preventDefault();
});

If that doesn't answer your question, please elaborate

Upvotes: 0

Luke
Luke

Reputation: 8407

change "click" event to "submit", and bind it not to btn but to form

$(document).ready(function () {
    $('#form1').on("submit", function (evt) {
        evt.preventDefault();
    });
});

Upvotes: 8

Related Questions