【发布时间】:2019-08-30 21:41:09
【问题描述】:
我已经设法获得一个表格,以根据选择下拉列表的值动态更改从 json 文件中提取数据。
我希望它使用默认值加载 - 在本例中为 2017
页面首次加载时没有表格。
谢谢
jQuery
$(document).ready(function (){
//Code below here is to dynamically change the table
let url = "students.json";
$.getJSON(url, function(response){
// The default value should be the value of the
let entryYear = "2017";
// code here is to record the change of the dropdown button
$("select.year").change(function(){
entryYear = $(this).children("option:selected").val();
//setup the table
let tableHTML = '<table>\
<tr>\
<th>Firstname</th>\
<th>Entry year</th>\
</tr>';
//for each of the records in the json file
//identify the students
$.each(response, function(index, student){
//identify the students who started in 2018
// https://www.formget.com/dynamically-change-form-action-based-on-selection-using-jquery/
if (student.entry_year === entryYear){
tableHTML +='<tr>\
<td>'+student.name+'</td>\
<td>'+student.entry_year+'</td>\
</tr>';
}
}
);//end each
//close the table tag
tableHTML += '</table>';
// add the data pulled to the html of the page in the div dynamic table
$('#dynamicTable').html(tableHTML);
}); //end .change
});// end json
}); //end ready
HTML
<form>
<select class="year">
<option value="2017" selected="selected">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
</select>
</form>
<div id="dynamicTable">
<!-- the dynamic table will go in here-->
</div>
.change 在更改下拉列表时有效,但初始页面加载不会产生表格
【问题讨论】:
标签: jquery dynamic html-table onchange