I am trying to have a button change its onclick and id attributes on the fly. But for some ready, I'm only able to change these attributes the first time.
$("#btn1").click(function () {
window.alert("im changing id to btn2 and ho ho ho");
$("#btn1").val("ho ho ho");
$("#btn1").attr("id", "btn2");
});
$("#btn2").click(function () {
window.alert("im changing id to btn1 and hey hey");
$("#btn2").val("hey hey");
$("#btn2").attr("id", "btn1");
});
Here is the example. I see that the id has changed, but the wrong onclick function is been called.
What I want to accomplish is the following:
- user enter some stuff on the form, then click search --> should return some data
- if there is data, then the button should change its id and onclick
- if not, remain the same
I would recommend you use a delegate on a higher element to bind the click to, i.e.:
Here is the solution in the jsFiddle: http://jsfiddle.net/WJTD5/4/
For me, I had to use something like what is posted below. Using the separate .val() and .attr() sections would NOT run in my code. This was the solution for me.
Hope this can help someone out.
Is there a reason you are changing the ID of the element? I would not recommend it and instead opt for using classes. Here is an example:
http://jsfiddle.net/WJTD5/2/
You are attaching the event before the id has changed to
btn2
, so$("#btn2")
is an empty collection. Bind the click handler in the first callback, like so:Here is a demonstration: http://jsfiddle.net/73zA2/
Alternatively, you can delegate event handling to an ancestor of the element:
Here is a demonstration of that approach: http://jsfiddle.net/2YKFG/