Im trying to select an option from a country dropdown menu through a chrome extension with javascript. When i select an option through the country dropdown menu normally, the values in the state dropdown change according to my selection.
I have tried selecting an option with many different methods, here are most of them:
$('#order_billing_country').val('CANADA').trigger("change")
$('#order_billing_country').val('CANADA').trigger('select')
$('#order_billing_country').val('CANADA').trigger('onselect')
Those past 3 but triggering select, onselect, and change
$('select').find('option[value=CANADA]').attr('selected','selected').end().trigger('onselect');
Nothing has worked... They change the value in the country dropdown but it doesnt trigger the changes in the state dropdown. Is there a way to select an option as if i was human, through javascript?...
Be careful because extensions have their own DOM, to access the page DOM I suggest you use a Content Script and a vanilla (pure) javascript to select and "manually" click.
window.addEventListener("load", function load(event) {
var optionToClick = document.querySelector('#order_billing_country').children[2]; //choose any of the children
optionToClick.selected = true;
simulateClick(optionToClick); // manual click simulation
});
function simulateClick(item) {
item.dispatchEvent(new PointerEvent('pointerdown', {bubbles: true}));
item.dispatchEvent(new MouseEvent('mousedown', {bubbles: true}));
item.dispatchEvent(new PointerEvent('pointerup', {bubbles: true}));
item.dispatchEvent(new MouseEvent('mouseup', {bubbles: true}));
item.dispatchEvent(new MouseEvent('mouseout', {bubbles: true}));
item.dispatchEvent(new MouseEvent('click', {bubbles: true}));
item.dispatchEvent(new Event('change', {bubbles: true}));
return true;
}
Hope it helps