Jquery .click() doesn't work after html has been changed
-
14-12-2019 - |
Question
It's pretty basic, I have a button, and when you click it, it changes. But after it changes the .click()
event doesn't work on it, but works on divs that are already on the page
$('#editBioButton').click(function(){
/* this captures html text and replaces it with textbox */
var oldBio = $('.bioText').html();
$('.bioText').replaceWith(' <textarea name="newBio" rows="6" cols="30" > ' + text + ' </textarea>');
/* this switches button */
$('#editBioButton').replaceWith(' <div id="saveBioText"> Save Changes </div> ');
/* this div won't react when clicked */
$('#saveBioText').click(function(){
alert('itowrks');
});
});
Solution
I ran into the same problem before. Turns out jQuery loses all bindings on elements that are added after loading. You should use the delegate
method
$("#editBioButton").delegate("#saveBioText", 'click', function(){
alert("this.");
});
OTHER TIPS
$('#editBioButton').click(function(){
var oldBio = $('.bioText').html();
$('.bioText').replaceWith(' <textarea name="newBio" rows="6" cols="30" > ' + text + ' </textarea>');
$('#editBioButton').replaceWith(' <div id="saveBioText"> Save Changes </div> ');
$(document).on('click', '#saveBioText', function(){
alert('it works');
});
});
use:
$(selector).live('click',function(){ });
The click method doesn't work on element added after that the page is been loaded, instead you can use the live method with click event
$("#editBioButton").live('click', function(){
...
});
The preferred way to write this is by using on
:
$(document).on("click", "#saveBioText", function() {
alert('this');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow