I'm opening a new window which contains a form like this
OpenedFormWindow = window.open(url, "popup_window", params);
var form_data = selected_option.data();
console.log(form_data);
OpenedFormWindow.onload = function() {
setTimeout(function() {
$.each(form_data, function (e, v) {
if (e.startsWith('field_')) {
e = e.slice(6);
var inputElement = $(OpenedFormWindow.document).find(':input[name="' + e + '"]');
console.log(inputElement);
inputElement.val(v);
inputElement.trigger('chosen:updated');
//console.log('test', inputElement.data('chosen'));
}
});
}, 500);
}
This form contains a Chosen dropdown that I am attempting to update. form_data is a key->value pair, where the key is the name of the element and the value is the value I want to set the dropdown to.
The dropdown in question is defined like this
<div class="mb-3">
<label class="form-label">Customer</label>
<?php
$customers = $pdo->all('SELECT id, name FROM customers');
?>
<select class="form-select" id="customer_dropdown" required name="customer_id">
<option></option>
<? foreach($customers as $customer): ?>
<option <?= $item_data['customer_id'] == $customer['id'] ? 'selected' : '' ?> value="<?= $customer['id'] ?>"><?= $customer['name'] ?></option>
<? endforeach; ?>
</select>
</div>
And Chosen is initialized in a separate js file.
$('select').not('.no_chosen,.ship_to_selector').chosen({ inherit_select_classes: true });
Very similar code works in other places in my system, but in this case the dropdown value is not updated. Note, I'm also passing a key->Value pair to update the Product Family input, which is working correctly, so I'm fairly sure this has to do with the Chosen plugin.
From the console.log in my $.each loop, I can tell the select element IS being picked correctly, and it appears that Chosen is fully initialized at this time, as the chosen-master class has been added to it, and the chosen-container div exists. Just in case, I did add a setTimeout around my $.each but this did not help. I have also verified that the value I am passing does exist in the chosen dropdown.
How can I update the dropdown in the opened window?


I was able to fix this by defining a function that loops over all of the active chosen elements and runs the chosen:updated trigger. This is defined in a global js file.
Then, I call that function from the opened window after updating the values.