I have a form and a button which is not a submit within the form.
I use jQuery to validate the form before submit.
I first have:
$('#btadd').live('click', function() {
$('#formadd').submit();
//return; //it doesn't matter
});
$('#formadd').submit(function() {
if (...) {
alert('incompleted!');
return false;
} else if (...) {
alert('invalid!');
return false;
} else
return true;
});
The problem is if the form is not completed, when I click button, the popup (‘incompleted!’) will occur twice.
Then I try to replace live with bind, then it works fine.
I have searched for the difference between live() and bind(), but still don’t know how they work in this example. My code works as what I want now, but I want to figure out what happen here. Can someone explain this to me?
live works for any element added to the DOM with that selector in contrast to bind that only works with elements already in the DOM. Let’s say you have an element
<div id="test">Test</div>. If that element exists at the time the bind method is called then the bind will work as expected. If instead the element does not exist then it will not work.This is in contrast with live that works with any element with the selector no matter when it is added to the DOM.