【问题标题】:How to change dropdown option value with Document.execCommand()如何使用 Document.execCommand() 更改下拉选项值
【发布时间】:2023-01-13 02:19:33
【问题描述】:
我正在尝试在 bigCommerce 结帐页面上预先填写值。由于结帐页面使用嵌入式反应,这就是我无法使用普通 javascript 方法更改字段值的原因。
虽然,我可以使用 Document.execCommand() 更改值。
这是更改名字的实际代码:
document.getElementById("firstNameInput").focus();
document.execCommand("insertText", false, customerInfo.firstName);
但问题是我无法使用 Document.execCommand() 从下拉菜单中更改/选择国家/地区。
所以我的问题是,如何使用 document.execCommand 更改下拉值?
附言:我知道 document.execCommand 已被弃用,但我现在没有任何可用的替代方法来更改值,因为正如我所说,纯 javascript 方法不会更改 bigcommerce 结帐页面上的字段值。
【问题讨论】:
标签:
javascript
jquery
bigcommerce
【解决方案1】:
I had the same issue, and found this solution:
var sel=document.querySelector('#id-of-your-selector');
sel.options[1].selected=true; //option no to be select here I am selection the option at index no# 1, you can change
var event = new Event('change', { bubbles: true }); //create his event
event.simulated=true; //add this too
sel.dispatchEvent(event);//dispatch event in this line sel is the element we created at first line for selector.