Question

Ok, so putting preventDefault on my submit button works to stop form submission. The consequence of this is that it won't tell the user of required fields and just performs the click event on the button.

Adding preventDefault to the submit handler shows the user the required fields, but still fires the click event tied to the button.

I need both.

<form action="" method="post">
  <input type="text" class="class" id="id" name="name" required="required" />
</form>

Now the js:

$("button").click(function(event){
  event.preventDefault();
  //performs function
});

This will fire the click event, regardless of a required form input.

$("form").submit(function(event){
  event.preventDefault();
});
$("button").click(function(){
  //performs function
});

This will show a required message to the user, but still perform the submit button function. How do I do both? I've looked at some other SO questions I could find on this but it seems most could be answered by adding preventDefault to form.submit.

Was it helpful?

Solution

I was actually trying to do two things when I only needed to do one.

I didn't need the button.click function at all since by default it submits the form. I just needed to put the button.click function inside form.submit instead.

$("form").submit(function(event){
    //perform button function
    return false;
});

OTHER TIPS

Manually fire the submit event.

$("button").click(function(event) {
     event.preventDefault();

     $('form').submit();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top