如何根据Ajax请求更改选择框所选选项

How to change select box selected option depending on Ajax request

本文关键字:选择 选项 何根 Ajax 请求      更新时间:2023-09-26

我有一个包含文本框和选择框的表单。我正在向PHP页面发送Ajax请求,并根据该请求自动填写此表单。填写文本框没有问题,但如何确定所选的选择框选项?任何帮助都会得到通知。

$(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 !");
            }         
        });
    });
});

要按照您尝试的方式进行操作,只需进行语法修复:

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

然而,你可以像做其他所有事情一样做:

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