I have a button that when clicked dynamically inserts a new row into a table. I want to be able to remove rows from this table, so I'm trying to use jQuery's .on() function to attach a click handler to a span element at the end of each row.... which works fine, except that when I click on the span to remove a single item, the click event is called for all items in the table.... and they're all removed. How do I hook it up so it calls just the row I clicked on handler? Here is my code:
Here is the js:
$("#milestonesList").on('click', 'span[id*="tempmilestone"]', function (e) {
$(this).each(function () {
$('span[id*="tempmilestone"]').each(function () {
alert("ON: " + $(this).attr("idx"));
_milestones = _milestones.slice(parseInt($(this).attr("idx"), 10));
buildMilestoneOutput(milestonesList);
});
});
});
Now no matter what row I click on, every row's click event is fired. What am I doing wrong?
I have tried this numerous ways, without the .each() functions and still it fires for every row in the table. Maybe if I show the rest of the code it would help:
Here is the buildMilestoneOutput function that gets called at the end:
function buildMilestoneOutput(container) {
container.innerHTML = "";
alert("Length: " + _milestones.length);
var s = "<table id='testscroll' style='width: 690px; padding: 10px;'><tr><td style='font-weight: bold;'>Title</td><td style='font-weight: bold;'>Description</td><td style='font-weight: bold;'>DueDate</td></tr>"
for (var i = 0; i < _milestones.length; i++) {
s += "<tr><td style='width: 300px; padding-bottom: 10px;'>" + _milestones[i].Title + "</td><td style='width: 350px; padding-bottom: 10px;'>" + _milestones[i].Description + "</td><td style='width: 30px; padding-bottom: 10px;'>" + _milestones[i].Name + "</td><td><span idx='" + i + "' style='margin-left: 5px; cursor: pointer;' id='tempmilestone'>remove</span></td></tr>";
}
s += "</table>";
container.innerHTML = s;
}
this original gets called when a user clicks an Add Milestone button:
$("#lbAddMilestone").click(function () {
milestonesList.innerHTML = "";
var newMilestone = new GoalMilestone();
newMilestone.Title = "New Milestone";
_milestones.push(newMilestone);
buildMilestoneOutput(milestonesList);
wireupMilestoneDeletes();
return false;
});
And here is the wireupMilestoneDeletes:
function wireupMilestoneDeletes() {
$("#milestonesList").on('click', 'span[id*="tempmilestone"]', function (e) {
alert("ON: " + $(this).attr("idx"));
_milestones = _milestones.slice(parseInt($(this).attr("idx"), 10));
buildMilestoneOutput(milestonesList);
});
}
eacheachs,$(this)already holds the item clicked.<span>elements with the same id because of<span idx='" + i + "' style='margin-left: 5px; cursor: pointer;' id='tempmilestone'>which can cause all sort of mumbo-jumbo. Try editing so it isid='tempmilestone"+i+"', then you increment the id and the selector with[id*='tempmilestone']should still work