May 27, 2013

Can't detect changed id

Xegano’s Question:

When I change the id of a button I cannot find the new id with on.(“click”). The function console.log() does detect that it’s changed but I cannot detect it with the on() function.

HTML:

<form id="formName" action="" method="post">
    <input type="submit" id="submitBtn" value="Submit" />
</form>
<button id="change">Change</button>

JS:

$("#change").on("click", function(){
    $("#submitBtn").attr("id", "NewBtn"); 
});

$("#formName").submit(function(e){
    e.preventDefault();
});

$("#NewBtn").on("click", function(){
    alert("Hello"); 
});

So I need it to alert “Hello” after I have clicked on change. It does change the id I checked that with inspect element.

Fiddle: http://jsfiddle.net/WvbXX/

.attr() function does not have a callback and thus it cannot be checked unless you setup an interval using setInterval but the function itself executes pretty soon so you are not going to need it.

For solving the problem in hand event delegation proposed by tymeJV is the right way to do it.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!