Reputation: 3998
I am using latest jQuery which says .live()
is deprecated and .on()
should be used instead.
I am having problem attaching click event to the button. I modify the button value dynamically and should be able to handle the two cases
<input type="text" ><input id="button_1" type="button" value="add" >
<input type="text"> <input id="button_2" type="button" value="add">
$('[id^="button_"]').on("click", "input", function() {
$(this).val("delete");
$('#button_'+$(this).attr('id').split('_')[1]).attr('id', 'delButton_'+$(this).attr('id').split[1]);
});
$('[id^="delButton_"]').on("click", "input", function() {
$(this).val("add");
$('#delButton_'+$(this).attr('id').split('_')[1]).attr('id', 'button_'+$(this).attr('id').split[1]);
});
This is the demo : jsfiddle
Upvotes: 1
Views: 541
Reputation: 71918
You can only delegate events to ancestor elements, but you're trying to delegate to a sibling. (Actually, I'm not sure what you're doing!)
So if your markup was
<div class="buttonContainer">
<input type="text" ><input id="button_1" type="button" value="add" >
</div>
You could use
$('.buttonContainer').on("click", "input", function() {
// here, "this" will be the clicked input
});
The above will delegate clicks on both the text input and the button to their parent div. Clicking on any of the elements will trigger the function.
If you only want to target the button, change the selector passed to .on
:
$('.buttonContainer').on("click", '[id^="button_"]', function() {
// here, "this" will be the clicked button
});
Upvotes: 6
Reputation: 21482
The equivalent of:
$('[id^="button_"]').live("click", function() {
Is:
$(document).on("click", '[id^="button_"]', function() {
But if you can use a closer ancestor than $(document)
, you should.
Upvotes: 1