MacMan MacMan - 4 months ago 20
jQuery Question

Change button id and value makes click() event fails

I have a button on my page made like this :

<input type='button' class='act' id='save' value='save'/>


Within the page I have a couple of click functions eg:

$("#save").click(function() {
alert ('save');
})

$("#update").click(function() {
alert ('update');
})


Using the following jquery elsewhere in the page I'm changing the button value and id.

$(".act").attr("id", "save").attr("value", "save");


OR

$(".act").attr("id", "update").attr("value", "update");


Looking at the element I can see the buttons ID and value are being updated. But the click functions fail following the change.

On first load the 'save' click works as the button has the ID save, following the change the element has got the ID 'update' but the update click isn't triggered.

What am I doing wrong ?

Thanks

Answer

Changing the id of an element isn't a great idea as they are meant to be static.

That being said, your code doesn't work as you attach the event handlers on load of the DOM. Therefore the same event is bound to the element, regardless of its id. To achieve what you require you need to use a delegated event handler, like this:

$(document).on('click', "#save", function() {
    console.log('save');
}).on('click', "#update", function() {
    console.log('update');
});

Note that document is used here purely as an example. In production code you should use the closest parent element that's available in the DOM on load of the page.

Comments