Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print first element from dropdown list on change?

I have this function :

function LoadRegions() {
    var region = $('#RegionID');


    var url = "/Account/GetRegions";
    $.getJSON(url, { countryId: $('#CountryID').val() }, function (response) {
        // clear and add default (null) option 

        //region.empty().append($('<option></option>').val('').text('Please select'));



        for (var i = 0; i < response.length; i++) {
            region.append($('<option></option>').val(response[i].Id).text(response[i].Name));
        }

    });
}

When user choose countrie i call this function but i want to display on start first element from that list... With this line i get "Please select" but i want first element from list:

  region.empty().append($('<option></option>').val('').text('Please select'));

If i comment this line i get blank...any help?

like image 399
uzhas Avatar asked Nov 01 '22 00:11

uzhas


1 Answers

I believe the problem could have been the issues with chaining. See the documentation for end().

The empty() and append() were being done on the same chain. This can sometimes cause issues because of the chaining algorithm. The documentation has good description of the issue.

This can fix your problem.

$.getJSON(url, {
    countryId: $('#CountryID').val()
}, function(response) {
    // clear and add default (null) option 
    region
        .empty()
        .end()
        .append($('<option>', {
            value: '',
            text: 'Please select'
        }));
    $.each(response, function(key, tocken) {
        region.append($('<option>', {
            value: tocken["Id"],
            text: tocken["Name"]
        }));
    });
});
like image 182
rrk Avatar answered Nov 12 '22 15:11

rrk