Adding elements as data to a table with change listeners

Adding elements as data to a table with change listeners

DLCDLC Posts: 4Questions: 0Answers: 0
edited October 2011 in General
Was wondering if there was a way to add input elements to the data as well as attach event listeners to them?

Right now I load in some json via ajax, generate a line like '' and then add it into the table with the rest of the row via fnAddData().

Afterwards I try to add change listeners like such:
[code]
$("input[type='checkbox']").change(function () {
console.log(this.name+ "changed status");
if ($(this).is(':checked')) {
$.getJSON(validate_url, function(resp) {
alert(resp['Response']+ ' validated');
});
} else {
$.getJSON(unvalidate_url + this.name, function(resp) {
alert(resp['Response']+ " removed validation");
});
}
});
[/code]

except they don't seem to be applied.

Is this an issue of when the data elements are actually added to the DOM, vs when the change listeners are applied? Is there a way I can add the change listeners?

Replies

  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    probably an issue of the dynamic elements being added after your listener code was run.

    jquery has a .live() routine to handle this. it continuously checks for new DOM elements that match the selector

    [code]$("input[type='checkbox']").live( 'change', function () {
    console.log(this.name+ "changed status");
    if ($(this).is(':checked')) {
    $.getJSON(validate_url, function(resp) {
    alert(resp['Response']+ ' validated');
    });
    } else {
    $.getJSON(unvalidate_url + this.name, function(resp) {
    alert(resp['Response']+ " removed validation");
    });
    }
    });
    [/code]
  • DLCDLC Posts: 4Questions: 0Answers: 0
    Thanks. It actually works now! Any reason why you mentioned live() and not delegate()?
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    honestly I don't know the difference between .live() and .delegate(). so no reason why I chose one over the other. looks like they are similar, with just some syntactic difference.. ?
  • DLCDLC Posts: 4Questions: 0Answers: 0
    Supposedly delegate is the newer and idiomatic way to do it. It uses live under the covers but is more efficient because it doesn't work on the entire document by default. It's what is used in JQuery Pocket Reference too.
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    Good to know, thanks. I'll read more up on it.
This discussion has been closed.