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