首页 > 解决方案 > 以编程方式选择浏览器中未更新的选项

问题描述

我正在尝试自动填充下拉选择器,特别是在这个网站上。请注意,当用户手动选择一个国家(比如英国)时,字段会发生变化,并且只显示邮政编码。

但是,我对如何通过 JavaScript 实现这一点有点困惑:

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

这只会更改下拉列表的值,但不会像手动用户那样“提交”或“单击”它。In other words, the State/PostCode fields don't dynamically change when another Country is selected.

我对如何进行有点困惑。

标签: javascript

解决方案


我创建了一个小提琴,我通过 JS 更改选择框的值,然后触发和 onchange 事件。然后根据选择框的值将选项附加到另一个选择框。

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

JS代码:

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);

推荐阅读