#jquery #dynamic #html-table #onchange
#jquery #динамическое #html-таблица #onchange
Вопрос:
Мне удалось получить таблицу для динамического изменения данных, извлекаемых из файла 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 работает при изменении выпадающего списка, но при начальной загрузке страницы таблица не создается
Ответ №1:
Что вы можете сделать, это создать функцию, которая генерирует таблицу, и просто передать ей год.
В моем примере я вызываю функцию при изменении, но я также использую ее вне любого события, чтобы она обрабатывалась при готовности страницы.
$.create_table = function(entryYear){
let url = "students.json";
$.getJSON(url, function(response){
//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 json
}
$(document).ready(function(){
$.create_table(2017);
$("select.year").change(function(){
$.create_table($(this).children("option:selected").val());
});
}); //end ready