문제

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.

도움이 되었습니까?

해결책

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;
});

다른 팁

Manually fire the submit event.

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

     $('form').submit();
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top