首页 > 解决方案 > 如何在 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 索引有效,但我需要如前所述更改它。

任何帮助将不胜感激!

海姆

标签: javascripthtml

解决方案


如果要更改组合框的默认(选定?)值,只需设置其 .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>


推荐阅读