I am trying to write a form that sends a JSON request to the server when a button on the form is clicked. I want to disable the default form behaviour so that clicking the button is what will do the job of sending an email address. The idea is to return a message from the server back to the form (if an error), or to replace the form with a success message (on success).
This is what I have so far (snippet):
<div>
<br />
<div class="row">
<div id="invite-member">
<p>Enter your email:</p>
<div class="no-show error-msg"></div>
<form id="frm-invite" method="post" autocomplete="off" action='www.example.com/backend.php' accept-charset="UTF-8">
<div class="input-append">
<input type="text" placeholder="Enter Email" class="input-long">
<button id="btn-invite" class="btn btn-primary btn-success" type="submit">Add me »</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#btn-invite").click(function(e){
alert('Woohoo');
e.stopPropagation();
});
});
</script>
The first time the page is loaded, the button behaves as expected. The subsequent times though (without reloading the page), the event binding seems to have been ‘broken’ and the browser wants to go to http://www.example.com/backend.php.
Why is that?.
In that case binding to the form submit may be better to prevent other means of submitting the form which cricumvent the button click.
on() is only usable in jQuery 1.7 and later, replace it with bind() if you are using a version of jQuery lower than 1.7
Also note that
return false;is equal to both,event.preventDefault();andevent.stopPropagation();.