JQuery.click () not working after html change
It's pretty simple, I have a button and when you click on it it changes. But after this change the event .click()
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');
});
});
+3
Thomas depole
source
to share
5 answers
I faced the same problem before. It turns out jQuery loses all bindings for post-loaded elements. You must use the methoddelegate
$("#editBioButton").delegate("#saveBioText", 'click', function(){
alert("this.");
});
+3
arvidkahl
source
to share
$('#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');
});
});
+2
adeneo
source
to share
using:
$(selector).live('click',function(){ });
+1
JensT
source
to share
The click method does not work on the added element after the page is loaded, you can instead use the live method with the clicked event
$("#editBioButton").live('click', function(){
...
});
+1
Marco calì
source
to share
The preferred way to write this is with on
:
$(document).on("click", "#saveBioText", function() {
alert('this');
});
0
MMachinegun
source
to share