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.


function updateDepartment(name, id, location) {

        url: "libs/php/getLocation.php",
        type: 'GET',
        dataType: 'json',
        success: function (result) {
            if ( == "ok") {
                $.each(, i => {
                    $('#editDepartmentLocation').append($("<option>", {
        error: function (error) {



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

Source: Ask Javascript Questions