0

I am trying to autofill a drop-down selector, specifically on this website. Notice that when the user manually selects a country (let's say United Kingdom), the fields change and only postcode appears.

However, I'm a bit stuck on how to achieve this via JavaScript:

let pageElement = document.getElementById('#checkout_shipping_address_country');
pageElement.focus();
pageElement.value = "United Kingdom";
pageElement.dispatchEvent(new Event('change'));
pageElement.blur();

This only changes the value of the dropdown but somehow doesn't "submit" or "click" it as if a manual user is doing it. In other words, the State/PostCode fields don't dynamically change when another Country is selected.

I'm a bit stuck on how to proceed.

JC1
  • 849
  • 13
  • 25
  • Does this help you https://stackoverflow.com/questions/78932/how-do-i-programmatically-set-the-value-of-a-select-box-element-using-javascript – Asutosh Aug 03 '20 at 04:36
  • Shouldn't `field.value` be `pageElement.value`? If not, what's field and where does it come from? – Dennis Hackethal Aug 03 '20 at 04:40
  • @weltschmerz yes sorry, error from copy + pasting. Updated :) – JC1 Aug 03 '20 at 04:41
  • @Asutosh no, the problem is that the subsequent input / select nodes don't dynamically change if you do it that way. – JC1 Aug 03 '20 at 04:46

1 Answers1

-1

I have created a fiddle, where I am changing the selectbox's value through JS, then triggering and onchange event. Then based upon the select box's value appending options to another select box.

https://jsfiddle.net/asutosh/18zs3ofd/20/

JS code:

document.querySelector("#checkout_shipping_address_country").addEventListener('change', function() {
  console.log(this.value);
  fillStates(this.value);

});
function fillStates(aCountryId) {
  const stateSelectbox = document.querySelector("#states");
  let optionsVal = [];
  switch (aCountryId) {
    case 'usa':
      optionsVal = ['phili', 'newyork'];
      break;
    case 'uk':
      optionsVal = ['london', 'britain'];
      break;
    default:
      break;
  }
  console.log(optionsVal);
 
  const optionsArray = optionsVal.map((optVal) => "<option value=" + optVal + ">" + optVal + "</option>");
  stateSelectbox.innerHTML = '';
  stateSelectbox.innerHTML = optionsArray.toString();
}

function selectElement(id, valueToSelect) {
  let element = document.getElementById(id);
  element.value = valueToSelect;
}
//Select USA option after 3 seconds of UI gets loaded
    setTimeOut(()=>{
    selectElement('checkout_shipping_address_country', 'usa');
    var changeEvent = new Event('change');
     document.querySelector("#checkout_shipping_address_country").dispatchEvent(changeEvent);
    },3000);
Asutosh
  • 1,775
  • 2
  • 15
  • 22