Question

I've a simple form

<form action="try.php" method="POST">
    <input id="name" name="name" type="text" placeholder="Name" />
    <input id="btn" name="" type="submit" value="Submit" />
</form>

When I click the submit button, I want to submit the form only if a certain condition is met; and if not, the form will not be submitted (instead show and alert). I do not want to change the markup here. So how do I make it sure that, even though I've provided <form action="try.php" method="POST">, the form doesn't get submitted if the condition is not fulfilled?

I want to do something like the code below.

//jQuery code   
$("#btn").live('click', function(event) {
      if(<condition is true>){
          //Show message
      } else {
         //Submit Form
      }
});
Was it helpful?

Solution

If you don't want to submit the form, you can prevent the default action using preventDefault()

if(<condition is true>){
      event.preventDefault(); 
  }

or return false; It's better to do the former unless you also want to stop the event from bubbling.

OTHER TIPS

You can use event.preventDefault() or return false;. Then you can easily submit the form with form.submit()

You have to add handler to form submit event, not to the button click.

Try something like this:

$('#form').submit(function() {
  if(<condition is true>) {
    alert('Fill all fields');
    return false; // will cancel default submit
  }

  // do something before submit
  // if necessary
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top