So this is my function, it deletes people from a list if you click on certain part of the form:
function ParticipantsDeleteClick(model, url) {
for (i in model.Participants) {
$("#delete" + i).click(function () {
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: model.Participants[i].Id }),
success: function (result) {
result ? $("#participant" + i).remove() : alert("Delete failed");
},
error: function () {
alert("Could not get a response from the server.");
}
});
});
}
}
For some reason, it doesn’t matter which person you click on, it will always delete the last person from the list. And it only works once because once the last “i” gets deleted, every other click function points to that dom element with the last i’s value.
I don’t know why every time I’m adding a click function it all points to the last i’s value in the loop. I modified the function adding a temp variable that took i’s integer value and that didn’t work either:
function ParticipantsDeleteClick(model, url) {
for (i in model.Participants) {
var temp = parseInt(i);
$("#delete" + temp).click(function () {
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: model.Participants[temp].Id }),
success: function (result) {
result ? $("#participant" + temp).remove() : alert("Delete failed");
},
error: function () {
alert("Could not get a response from the server.");
}
});
});
}
}
So I’m not sure how I can get this to work.
iis always overwritten in the loop. You need a closure, eg by using$.each(function(){..}, or by wrapping the loop’s body in a self-invoking function.