Select2 field .value property doesn't change inside .onchange function
See original GitHub issueI’m having this very specific issue of which I have not been able to find a solution. I have a Select2 field on which after selecting a specific company it will auto fill with it’s corresponding country based on values fetch from an API on a .onchange function triggered on a Select2 field from which you select the corresponding company to fetch from.
All other auto-filled fields apart from this one, get populated with it’s corresponding value, except for the Select2 field for the country value that only gets selected but not displayed has chosen.
However, if I try to change the .value property outside the .onchange function, the field does change completely and display the currently selected country on the list.
I already tried executing the function either by changing the .value property with vanilla JavaScript and using the .val method with JQuery following the recommendations on the Select2 documentation, but the same result occurs, here I attach the code and some screenshots.
const countryField = document.querySelector(
'select[name=' + country + ']'
)
selectField.onchange=function() {
const apiUrl = new URL(url)
const params = {q: $(this).val()}
apiUrl.search = new URLSearchParams(params).toString();
fetch(apiUrl)
.then((response) => response.json())
.then(function(data) {
const fieldsToUpdate = [
{field:addressLine1Field,value:data.address_line1},
{field:addressLine2Field,value:data.address_line2},
{field:cityDistrictField,value:data.city_district},
{field:stateProvinceField,value:data.state_province},
{field:postalCodeField,value:data.postal_code},
{field:countryField,value:data.country},
]
for (const { field,value } of fieldsToUpdate) {
if (!!field) {
field.value = ''
if (!!value) {
field.value = value
}
}
}
})
.catch(function(error) {
console.log(error);
});
}
While changing the property outside the function results in this:
const countryField = document.querySelector(
'select[name=' + country + ']'
)
countryField.value = 'Canada'
So far I’m still not sure what makes the property change works different on the DOM while executing it inside the .onchange method. If anyone out there might have any idea what it could be, any help would be appreciated. Thank you all.
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
Are you able to reproduce this issue in a jsbin (doesn’t need to be a fancy example) so we can use it for an isolated test case? That should make it easier to trace the issue, since it sounds specific to how the browser binds to this event.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.