简体   繁体   中英

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.

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

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

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

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