Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change button id and value makes click() event fails

Tags:

jquery

onclick

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

like image 949
MacMan Avatar asked Jan 06 '23 14:01

MacMan


2 Answers

try this

$("#btn1").click(function () {
window.alert("im changing id to btn2 and ho ho ho");
$("#btn1").val("ho ho ho");
$("#btn1").attr("id", "btn2");

$("#btn2").unbind("click").click(function () {
    window.alert("im changing id to btn1 and hey hey");
    $("#btn2").val("hey hey");
    $("#btn2").attr("id", "btn1");    
});
});

or delegate method

$("#btn1").parent().on("click","#btn1", function () {
    window.alert("im changing id to btn2 and ho ho ho");
    $("#btn1").val("ho ho ho");
    $("#btn1").attr("id", "btn2");   
})
.on("click","#btn2",function () {
    window.alert("im changing id to btn1 and hey hey");
    $("#btn2").val("hey hey");
    $("#btn2").attr("id", "btn1");    
});

How to change the attr and id of a button after clicking? using jquery?

like image 146
Wenson Avatar answered Jan 19 '23 01:01

Wenson


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.

like image 41
Rory McCrossan Avatar answered Jan 19 '23 01:01

Rory McCrossan