Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate table based in select

I am using this code to populate a table based in the select option chosen. This code works fine if the user click in the select, but not if the user uses the arrow keys.

In that case the table is not cleaned, and the data from json is populated sequentially. So, the output in table will not match the current selected option.

Any idea 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>');
        });
    });
});
like image 280
user455318 Avatar asked Nov 28 '25 10:11

user455318


1 Answers

One solution you can look at is to abort 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;
    });
});
like image 143
Arun P Johny Avatar answered Nov 29 '25 22:11

Arun P Johny