How to add dynamic selected option to a dynamically populated select list?

I’m trying to set the selected option text for a select menu to be whatever location is – this parameter has been passed into the updateDepartment function dynamically from a previous PHP request.

The AJAX function that follows calls to another PHP file to dynamically populate the #editDepartmentLocation select menu with a list of text/value option pairs. One of the names in this list will always match whatever location parameter is passed into the function.

I’m able to set the value of #editDepartmentName to the name parameter as this is just a text input, however when I try to add $("#editDepartmentName").val(location) this does not work and the selected option just defaults to the item at the top of the list, even though the value of location is present in the list.

Is there a way to get around this?

Thanks for any help.

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>

Source: Ask Javascript Questions

LEAVE A COMMENT