Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine jQuery preventDefault and required form inputs

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.

like image 245
o_O Avatar asked Jun 01 '13 06:06

o_O


1 Answers

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;
});
like image 172
o_O Avatar answered Oct 21 '22 12:10

o_O