我正在尝试添加一个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> ' + (rowCount + 1) + ' </td>'
$.ajax({
url: "/AssignExercisesViewModel/InitialiseExercises",
datatype: "json",
traditional: true,
success: function (result) {
oTable.fnAddData([
'<tr style="border:1px solid black" class="exercise-records"><td> ' + (rowCount + 1) + ' </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循环读取。
答案 0 :(得分:1)
在将其放入oTable.fnAddData
数组
var tblRow = '<tr style="border:1px solid black" class="exercise-records">';
tblROw += '<td> ' + (rowCount + 1) + ' </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> ' + (rowCount + 1) + ' </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']);