user455318
user455318

Reputation: 3346

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>');
        });
    });
});

Upvotes: 3

Views: 1254

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388326

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;
    });
});

Upvotes: 6

Related Questions