如何将for循环添加到数据表中添加新行

时间:2016-02-15 05:42:26

标签: jquery datatable

我正在尝试添加一个for循环,它会在我的下拉框中显示一个项目列表。但是我不确定如何将它插入我的datatable.fnAddData。

var oTable;

$(document).ready(function () {

oTable = $('#TempTable6').dataTable({
    responsive: true
});

$("#addNew").click(function (e) {
    var rowCount = $('.exercise-records').length;
    var html = '<tr style="border:1px solid black" class="exercise-records"><td>&nbsp;&nbsp;&nbsp;' + (rowCount + 1) + '&nbsp;&nbsp;</td>'
    $.ajax({
        url: "/AssignExercisesViewModel/InitialiseExercises",
        datatype: "json",
        traditional: true,
        success: function (result) {

         oTable.fnAddData([
          '<tr style="border:1px solid black" class="exercise-records"><td>&nbsp;&nbsp;&nbsp;' + (rowCount + 1) + '&nbsp;&nbsp;</td>',
             '<td><select class="form-control" data-val="true" data-val-number="The field ExerciseRegionID must be a number." id=ddlRegion' + rowCount + ' name=[' + rowCount + '].ExerciseRegionID><option value="">Select an Exercise Region</option>' +
                'for (var i = 0; i < '+ result.data.length +'; i++) {' +
                   '<option value= ' +result.data[i].Value +'>' +  result.data[i]+'         </option>' +
                 '}'
            //more columns with additional  information
         ]);
        }
    });
    e.preventDefault();    
});
}

上面的代码是与添加新行相关的代码,您可以看到我已经插入了for循环。但是当我运行for循环时出现错误,我不确定我应该如何编写它以允许它将其作为for循环读取。

2 个答案:

答案 0 :(得分:1)

在将其放入oTable.fnAddData数组

之前,先将其保存为字符串
var tblRow = '<tr style="border:1px solid black" class="exercise-records">';
    tblROw += '<td>&nbsp;&nbsp;&nbsp;' + (rowCount + 1) + '&nbsp;&nbsp;</td>';
    tblROw += '<td><select class="form-control" data-val="true" data-val-number="The field ExerciseRegionID must be a number." id=ddlRegion' + rowCount + ' name=[' + rowCount + '].ExerciseRegionID><option value="">Select an Exercise Region</option>';

for (var i = 0; i < result.data.length ; i++) {
    tblRow += '<option value= ' +result.data[i].Value +'>' + result.data[i]+'</option>';
}

tblRow += '</select>';
tblRow += '</td>';
tblRow += '</tr>';

tblRow

中添加oTable.fnAddData
oTable.fnAddData([ 
    tblRow       
    //more columns with additional  information
]);

答案 1 :(得分:1)

尝试使用each并首先构建选项列表并使用row.add向数据表添加新行

var option =  [];

    $.each(result.data,function(i,v) {
      option.push('<option value= "' +v.Value +'">'+v+'</option>')
    }

        oTable.row.add(['<tr style="border:1px solid black" class="exercise-records"><td>&nbsp;&nbsp;&nbsp;' + (rowCount + 1) + '&nbsp;&nbsp;</td><td><select class="form-control" data-val="true" data-val-number="The field ExerciseRegionID must be a number." id=ddlRegion' + rowCount + ' name=[' + rowCount + '].ExerciseRegionID><option value="">Select an Exercise Region</option>' + option +'</select>//more columns with additional  information']);