2

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.

1
  • 1
    Please don't use "leetspeak". There is no character limit for questions. It's "are" not "r". Commented Jun 18, 2013 at 9:15

2 Answers 2

8

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

$(document).ready(function () {
    $('#form1').on("submit", function (evt) {
        evt.preventDefault();
    });
});
Sign up to request clarification or add additional context in comments.

7 Comments

but what if i have more than one button on the form
why do you care? I thought we are talking about submitting the form. You can have 5 submit buttons within the form - no one would work as the "submit" event triggers the post back
we r talking about preventing the post back with the required html5 feature intact.This won't work in case i have more tha n 1 button on the form
@iBlue" Why? Have you tried it at all? Please elaborate. It works fine for me: jsfiddle.net/8uk3b/1.
yeah in your fiddle you are using it not correctly. If you want two seperate field, with two seperate buttons, you of course should use two seperate forms :)
|
0

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

1 Comment

please read comments om Luke's answer, and have a look a this jsfiddle.net/8uk3b/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.