Populating a selection-based table

I am using this code to populate a table based on a selected select option. This code works fine if the user presses the select button but not the user who is using the arrow keys.

In this case, the table is not cleared, and the data from json is filled sequentially. Thus, the output in the table will not match the currently selected option.

Any ideas about this?

$('select').on('change', function() {
    $('.agencies_table').html('');
    $.getJSON("/users/agencies/" + this.value, function(data) {
        $.each(data.json_list, function(i, obj) {
            $('.agencies_table').append('<tr> <td>' + obj.label + '</td> </tr>');
        });
    });
});

      

+3


source to share


1 answer


One solution you might look at is to interrupt the previous call



var xhr;
$('select').on('change', function () {
    if (xhr) {
        xhr.abort();
    }
    $('.agencies_table').html('');
    xhr = $.getJSON("/users/agencies/" + this.value, function (data) {
        $.each(data.json_list, function (i, obj) {
            $('.agencies_table').append('<tr> <td>' + obj.label + '</td> </tr>');
        });
    }).always(function () {
        xhr = undefined;
    });
});

      

+5


source







All Articles