简体   繁体   中英

How to change select box selected option depending on Ajax request

I have a form that contains textboxes and a selectbox. I am sending and Ajax request to a PHP page and i'am filling this form automatically depending on that request. There is no problem about filling textboxes but how can determine the selected select box option ? Any help would be appriciated.

$(document).ready(function(){
    $("#companyFillSelectBox").change(function(){
        var value = $("select#companyFillSelectBox option:selected").val();
        $.ajax({
            type: 'POST',
            url: 'companyFill.php',
            dataType: "json",
            data:{companyID:value},
            success:function(answer){
                $('#companyNameText').val(answer[0].companyName);
                $('#companyAddressTextArea').val(answer[0].companyAddress);
                $('#companyNetAdressText').val(answer[0].companyWebAddress);
                $('#companyPhoneText').val(answer[0].companyPhone);
                $('#companyFaxText').val(answer[0].companyFax);
                $('#companyCeoText').val(answer[0].companyCeo);
                $('#companyHRText').val(answer[0].hrDirector);
                $('#numOfIengText').val(answer[0].numOfIENG);
                $('#numOfEngText').val(answer[0].numOfENG);
                $('#numOfWhiteCollarsText').val(answer[0].numOfIENG);
                $('#totalEmpText').val(answer[0].numOfEmployees);
                $('#establishmentYearText').val(answer[0].yearOfEstablishment);
                $("#fieldOfBusinessSelectBox option[value=answer[0].yearOfEstablishment]").attr('selected', 'selected');
            },
            error:function(){
                alert("An error has occured !");
            }         
        });
    });
});

To do it the way you attempted would have just taken a syntax fix:

$("#fieldOfBusinessSelectBox option[value=" + answer[0].yearOfEstablishment +"]").attr('selected', 'selected');

However, you can do it the same way you did all the others:

$("#fieldOfBusinessSelectBox").val(answer[0].yearOfEstablishment);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM