I have multiple function objects declared from the same function that deal with their own tables with dynamically added rows. I need to have a delete button of some kind for each row. Since there can be multiple of these objects, the row must know what object it is a part of, and the object could be nested in some arbitrary scope inside other objects (and out of reach of some arbitrary function declaration, I think?), the typical solution of an onClick referencing some other javascript function doesn’t seem sufficient. I’ve got a setup using delegate to catch the click, but I’m not sure where to go from there. Here’s some example code:
function testobject() {
//other stuff
$stateadd.click(function() {
if ($stateselect.val() in states) { //already in array
} else {
$temp = $("<tr><td nowrap>" + USStates[$stateselect.val()].Name + "</td><td><input type=\"button\" class=\"testthing\" value=\"Remove\" /></td>").appendTo($selectedstates);
$temp2 = $temp.find('.testthing');
$temp.delegate($temp2, 'click', function(e) {
//how to know what row to delete? how to know which object the row is in?
alert($(e.target).attr('class')); //returns proper class, so I can get the button object itself
});
states[$stateselect.val()] = $temp;
}
});
//other stuff
}
To be clearer, I need two things in the click event: the testobject instance that made the row, and the $stateselect.val() id associated with that row. I can’t just delete the row tr/td tags, I need to have it removed from the states object as well.
Use
thisto refer to the element which is clicked and then you can find the corresponding parenttrelement using jQueryclosest()method.Also the first argument of
delegateis the selector on which the delegated event should work. You were passing a jQuery object so it didn’t work. Try this.jQuery
closest()gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.If you are using latest jQuery ver(1.7+) you can use
onmethod.Note: You should keep this code outside
testobjectmethod because you don’t need to adddelegateoroneverytime you calltestobjectmethod.Update: Based on the comments
Add a data attribute to the input remove button with stateselect value.
Js change