0

I am using HTML5 validation and jQuery for ajax and other functionality. I have a form and I have added validation in input types i.e. <input id="country" type="search" value="" required />

Now the problem is, form never post until I have filled valid values then I need to make an ajax call rather traditional form post. If I add an event like this

<form id="objectForm" method="POST" action="#!/" onsubmit="return submitData();"> it works but like this

$('.signinButton').unbind('click').click(function() {
    submitData();
});

browser validation doesn't work.

Any suggestions what can be done here.

Thanks, WA

3
  • 1
    bind your event handler to the form submit event not to the click of the submit button Commented Dec 28, 2011 at 8:26
  • does control reaches inside $('.signinButton').unbind('click').click(function(){}? Commented Dec 28, 2011 at 8:27
  • It worked for $('#objectForm').submit(function(){}); Thanks Phil Commented Dec 28, 2011 at 8:31

1 Answer 1

1

As indicated in the comments, you'll want to bind to the form submit, not the actual button click (what happens if they hit the enter key and the browser automatically submits the form?). Conventionally, you should only have one form tag per a page, so you generally should be safe using the generic $("form") selector. However, if you do have multiple forms (or just want to be extra cautious) you can grab it by the id selector of the form.

You indicate that you want to capture the event, and instead use an Ajax call (as opposed to allowing a postback. That being the case, something like the following example would work well. The key is you have to stop the default of the form element to prevent it from doing a postback.

$(function () {
  $("#objectForm").submit(function (e) {
    if (validationPasses) {
      callAjaxFunction();
    }
    e.preventDefault(); 
    e.stopPropagation();  // this one isn't always necessary, but if you really want to make sure (like if you, for some reason, have nested form elements) that the event is stopped in its tracks, calling both helps.
  });
});
Sign up to request clarification or add additional context in comments.

Comments

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.