Reputation: 2400
I am calling some forms using ajax, and then binding an event handler for every button. The problem is... when I call a new form using ajax the event handler is called again for the new elements and then it's added twice for the previous elements. How can I detect if an event handler is already on an element and not bind it again?
function x(){
$("input:button").click(function(){
alert('is this called once?');
});
}
<input type='button' value='Disable me' />
<input type='button' value='Disable me' />
function x(){
$("input:button").click(function(){
alert('is this called once?');
});
}
// calling event twice simulating an ajax calling:
x();
x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='button' value='Disable me' />
<input type='button' value='Disable me' />
Upvotes: 1
Views: 3373
Reputation: 5081
Does the click handler actually need to be re-added every time your AJAX request is called? If not, consider revising your code like so:
//Only call this once; new buttons will still trigger it
$(document).on('click', 'input:button', function() {
alert('is this called once?');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='Disable me' />
<input type='button' value='Disable me' />
By attaching the handler to the document and supplying a selector ('input:button'
), the function only triggers when clicking on buttons, but will automatically apply to any new buttons that are added after the initial binding.
Upvotes: 3
Reputation: 5466
One way to do this is use off
function of jQuery to remove any event attached and then attach it.
This is make sure there is only one click event attached to element.
Example Snippet:
function x() {
$("input:button").off('click').on('click', function() {
console.log('is this called once?');
});
}
// calling event twice simulating an ajax calling:
x();
x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='Disable me' />
<input type='button' value='Disable me' />
Upvotes: 4