javascript - 以编程方式选择浏览器中未更新的选项
问题描述
我正在尝试自动填充下拉选择器,特别是在这个网站上。请注意,当用户手动选择一个国家(比如英国)时,字段会发生变化,并且只显示邮政编码。
但是,我对如何通过 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.
我对如何进行有点困惑。
解决方案
我创建了一个小提琴,我通过 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);
推荐阅读
- deep-learning - PyTorch - 模型参数权重的意外形状
- python - 如何更新嵌套字典中的值
- c++ - 评估变量的构造函数等价物
- ms-word - 使用 gtsummary 和 flextable 在 rmarkdown 中生成表
- websocket - Mosquitto Broker 服务拒绝在 websockets 上启动
- mysql - 在多个条件下连接四个表
- c - 如何使用 C 程序永久存储信息?
- python - Scrapy Parse 回调未定义
- node.js - 在热中更新 MacOS 上的 Node.js 引发异常错误
- javascript - React + Formik - 如何传入新值并将表单设置为脏?