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


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


source


$('#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


source


using:

$(selector).live('click',function(){ });

      

+1


source


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


source


The preferred way to write this is with on

:

$(document).on("click", "#saveBioText", function() {
  alert('this');
});

      

0


source







All Articles