Динамическое изменение таблицы jQuery - PullRequest
0 голосов
/ 09 апреля 2019

Мне удалось получить таблицу для динамического изменения извлечения данных из файла 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 Ответ

0 голосов
/ 09 апреля 2019

Что вы можете сделать, это создать функцию, которая генерирует таблицу и просто передает ей год.

В моем примере я вызываю функцию при изменении, но у меня также она есть вне любого события, чтобы онапроцессы на странице готовы.

$.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
...