Wolf Larsen Wolf Larsen - 7 months ago 25
HTML Question

Set selected option JQuery

I am using jquery-1.12.3.min.js and dynamically get options for select

function loadCompanies() {
if ($("#isSubsidiaryCompany").is(":checked")) {
$.ajax({
type : "GET",
url : "get_companies",
success : function(data) {
$.each(data, function(i, data) {
$('#companiesList').append($('<option>', {
value : data.id,
text : data.name
}));
});
}

})
$("#companiesSelect").show();
$('#companiesList').val(data.id);
} else {
$("#companiesSelect").hide();
}


I want to set option selected but
$('#companiesList').val(data.id)
doesn`t work, could you suggest me the right way do achieve this, thanks in advance

Answer

You are setting the value outside of the AJAX callback function. Which means that those options are not guaranteed that they will be there. Put your code into the success callback:

if ($("#isSubsidiaryCompany").is(":checked")) {
    $.ajax({
        type : "GET",
        url : "get_companies",
        success : function(data) {
            $.each(data, function(i, data) {
                $('#companiesList').append($('<option>', {
                    value : data.id,
                    text : data.name
                }));
            });
            $("#companiesSelect").show();               // < === HERE ===
            $('#companiesList').val(data.id);
        }

    })
// ...

Also, to which data are you referring to in your .val(data.id)?