Kunal Vijan Kunal Vijan - 1 month ago 10
jQuery Question

Array is always picking the first value instead of specific value

refreshFileList = function() {
$("#filedetails tr").remove();
for (i = 0, j = fileDetails.length; i < j; ++i) {
$("#filedetails").append("<tr data-filesize='" + fileDetails[i].SIZE + "' data-filename='" + fileDetails[i].KEY + "'><td><strong>" + fileDetails[i].FILENAME + "</strong></td><td class='nodesize'>" + fileDetails[i].SIZE + " MB</td><td>" + fileDetails[i].EXT + "</td>" + fileDetails[i].TAG + "</tr>");
}
},

fileDelete = function(e) {
e.preventDefault();
var parentRow = jQuery(this).closest('tr')
, fileName = fileDetails[i].KEY
, fileSize = fileDetails[i].SIZE;
ajaxFileDelete(fileName, parentRow, fileSize);
},


Into the fileDelete function I don't want to use data-filename and data-filesize but when I am going to use fileName = fileDetails[i].KEY or fileSize = fileDetails[i].SIZE its always deleting the first value of the array instead of specific value but with data-attributes it working as expected.

Answer

Add i to the <tr> as a data attribute.

refreshFileList = function() {
  $("#filedetails tr").remove();
  for (var i = 0, j = fileDetails.length; i < j; ++i) {
    $("#filedetails").append("<tr data-index='" + i + "'><td><strong>" + fileDetails[i].FILENAME + "</strong></td><td class='nodesize'>" + fileDetails[i].SIZE + " MB</td><td>" + fileDetails[i].EXT + "</td>" + fileDetails[i].TAG + "</tr>");
  }
},

fileDelete = function(e) {
  e.preventDefault();
  var parentRow = jQuery(this).closest('tr')
    , i = parentRow.data('index')
    , fileName = fileDetails[i].KEY
    , fileSize = fileDetails[i].SIZE;
    ajaxFileDelete(fileName, parentRow, fileSize);
},
Comments