如何将动态选择的选项添加到动态填充的选择列表?

时间:2021-05-12 11:59:39

标签: javascript jquery ajax drop-down-menu html-select

我正在尝试将选择菜单的选定选项文本设置为 location 的任何内容 - 此参数已从先前的 PHP 请求动态传递到 updateDepartment 函数中。

调用另一个 PHP 文件后的 AJAX 函数,以使用文本/值选项对列表动态填充 #editDepartmentLocation 选择菜单。此列表中的 name 之一将始终匹配传递给函数的任何 location 参数。

我可以将 #editDepartmentName 的值设置为 name 参数,因为这只是一个文本输入,但是当我尝试添加 $("#editDepartmentName").val(location) 时,这不起作用,所选选项只是默认值到列表顶部的项目,即使 location 的值存在于列表中。

有没有办法解决这个问题?

感谢您的帮助。

JS:

function updateDepartment(name, id, location) {

    $.ajax({
        url: "libs/php/getLocation.php",
        type: 'GET',
        dataType: 'json',
        success: function (result) {
            console.log(result);
            if (result.status.name == "ok") {
                $.each(result.data, i => {
                    $('#editDepartmentLocation').append($("<option>", {
                        text: result.data[i].name,
                        value: result.data[i].id,
                    }));
                });
            };
        },
        error: function (error) {
            console.log(error);
        }
});

    $("#editDepartmentName").val(name);
    $("#editDepartmentLocation").val(location);

HTML:

<div class="form-group">
                <label for="name">Name:</label>
                <input type="text" value="" class="form-control" id="editDepartmentName" required>
              </div>
              <br>
              <div class="form-group">
                <label for="location">Location:</label>
                <select class="form-control custom-select" id="editDepartmentLocation" required>
                </select>
                </div>

1 个答案:

答案 0 :(得分:0)

Ajax 是异步的,因此“editDepartmentLocation”很可能尚未填充。 尝试移动:

$("#editDepartmentName").val(name);
$("#editDepartmentLocation").val(location);

在成功函数中。或者做一个比较:

var option =  $("<option>", {
                    text: result.data[i].name,
                    value: result.data[i].id,
});

if (result.data[i].id == location){
    option.attr("selected", "selected");
}

$('#editDepartmentLocation').append(option);