javascript - 如何在 JavaScript 中编辑组合框的默认值
问题描述
我需要你的帮助。我正在尝试更改 javascript 函数中组合框的默认值。
它应该是当我单击单选按钮时。单选按钮的函数调用是可以的,但是我没有成功更改组合框的默认值。
function contractRoleClick(option)
{
var assetsComboBox = document.getElementById("sellersAssetsCombobox");
assetsComboBox.disabled = true; //irrelevant
if (option.value == 2)
{
document.getElementById('sellersAssetsCombobox').option[0].value = "bbb"; //not working
document.getElementById("sellersAssetsCombobox").selectedIndex = 0; //the only line that work, but I don`t need it!
document.getElementById("sellersAssetsCombobox").options[0] = "aaa"; //not working
document.getElementById("sellersAssetsCombobox").options.item(0).text = "asd"; //not working
}
}
<select class="custom-select" disabled id="sellersAssetsCombobox" onchange="getAssetDetails(this)">
<option value="0" selected="" >Open this to select Seller`s assets</option> <!--I want to change this value-->
<option value="1">Code: 15524 -> Value: 366 ETH</option>
<option value="2">Code: 74121 -> Value: 841 ETH</option>
<option value="3">Code: 66473 -> Value: 510 ETH</option>
</select>
当我单击单选按钮时,该功能应将默认值“打开此以选择卖方的资产”更改为新值:“打开此以选择您的资产”,并将任何先前选择的值重置为新值。重置为 deaflut 索引有效,但我需要如前所述更改它。
任何帮助将不胜感激!
海姆
解决方案
如果要更改组合框的默认(选定?)值,只需设置其 .value。您不需要移动选项。
如果要更改选项的文本,请使用 .innerHTML
function contractRoleClick(option) {
document.getElementById("sellersAssetsCombobox").value = option;
}
function changeTextOfSelected() {
document.getElementById('sellersAssetsCombobox').options[
document.getElementById('sellersAssetsCombobox').selectedIndex
].innerHTML = 'Changed this ' + Math.random()
}
btn1.addEventListener('click', () => contractRoleClick(1));
btn2.addEventListener('click', () => contractRoleClick(2));
btn3.addEventListener('click', () => {
contractRoleClick(3); changeTextOfSelected();
});
<select class="custom-select" id="sellersAssetsCombobox" onchange="getAssetDetails(this)">
<option value="0" selected="" >Open this to select Seller`s assets</option> <!--I want to change this value-->
<option value="1">Code: 15524 -> Value: 366 ETH</option>
<option value="2">Code: 74121 -> Value: 841 ETH</option>
<option value="3">Code: 66473 -> Value: 510 ETH</option>
</select>
<button id="btn1">Select 1</button>
<button id="btn2">Select 2</button>
<button id="btn3">Select and Change 3</button>
推荐阅读
- axios - 如何在 axios PUT 请求中传递参数?
- java - Swing JFrame GUI 窗口在运行时为空
- git - 提交挂钩上没有此类文件或目录错误
- node.js - 单独的 Vue 前端和 Express 后端的 NGINX 设置
- c++ - 如何用笔画分割二值图像?
- python-3.x - 在传递另一个小部件的命令后,Tkinter 小部件不会消失
- c# - 字符串中的变量替换
- post - 将站点克隆到开发服务器时,Laravel 5.4 POST 方法停止工作
- typescript - 打字稿访问器命名约定
- python - 具有多列的 matplotlib 条形图,x 轴上的日期