Timothée HENRY
Timothée HENRY

Reputation: 14604

Jquery event is not always triggered

I have a Jquery event which does not trigger every time:

http://jsfiddle.net/LphjL/

My code:

thisWebsite = websiteInitialization ();

function websiteInitialization () {
    companyName = "name";
    var thisWebsite = new websiteConstructor(companyName);
    return thisWebsite;
}

function websiteConstructor(companyName) {
  this.companyName=companyName;
}

function ajaxUpdateDB(websiteElement, value) {
    return $.post('/echo/html/',{html: "<p>Text echoed back to request</p>",delay: 3}
                ,function(a){}
                ,"json"
        );    
}

function updateDatabase(websiteElement, value) {
    var promise = ajaxUpdateDB(websiteElement, value);
    promise.complete(function () {
        thisWebsite[websiteElement] = value;
    });
}


$(document).ready(function() {

    $(".websiteElement").change(function() {
        updateDatabase( $(this).attr('id'), $(this).val() );
    });

    $("#infos").click(function() {
        htmlCode =    "<input class='websiteElement' id='companyName' type='text' value='"+thisWebsite.companyName+"'>";
        $("#panel-content").html(htmlCode);
    });

    $("#homepage").click(function() {
        htmlCode = "homepage";
        $("#panel-content").html(htmlCode);
    });

});
​

As you can see in the jsfiddle, the first time the input field is updated the Ajax is triggered, but:

if you click on 'Homepage', then click back on 'Generic infos' and update the input field again this time the Ajax is NOT triggered: $(".websiteElement").change event is not called the second time.

Upvotes: 0

Views: 132

Answers (1)

Kevin B
Kevin B

Reputation: 95027

You need to bind the event using event delegation, or rebind the event after you replace the element. Below is the event delegation option:

$("#panel-content").on("change",".websiteElement",function() {
    updateDatabase( $(this).attr('id'), $(this).val() );
});

If the event is bound directly on the element, the event will be lost when the element is replaced/removed.

Upvotes: 1

Related Questions