I am facing a problem with a select
element that I cannot change programmatically. Initially, the select
has only one option
:
The initial HTML structure looks like this:
<select id="clients" name="client">
<option>Existing Clients...</option>
</select>
After fetching clients through an AJAX request, I add them dynamically to the select
:
getClients();
function getClients() {
$.get('ajax/get-clients.php')
.done(function(response) {
for (let client of JSON.parse(response)) {
addClientOption(client.id, client.company_name);
}
})
.fail(function(response) {
console.log(response);
});
}
function addClientOption(id, name) {
let newOption = document.createElement('option');
newOption.value = parseInt(id);
newOption.text = name;
document.getElementById('clients').appendChild(newOption);
}
Now the select
contains multiple options:
<select id="clients" name="client">
<option>Existing Clients...</option>
<option value="6">Number1</option>
<option value="77">SecondROUND</option>
<option value="14">Whips Dat Llama</option>
</select>
I then try to change its selected value using JavaScript:
console.log(document.getElementById('clients').value); // => "Existing Clients..."
document.getElementById('clients').value = 6; // expecting "Number1"
console.log(document.getElementById('clients').value); // => ""
// The select element still displays the "Existing Clients..." option.
Even after trying hard-coding the options directly into the select
, it works as expected. The issue seems to be specific to dynamically adding options. While I can find a workaround, I would appreciate an explanation for why this behavior is happening.