添加删除的选择选项

时间:2017-10-04 20:11:37

标签: javascript

目前我有一个我创建的功能,它根据从另一个选择传递的值从选择菜单中删除一些选项。我想在每次调用函数时恢复正常(将所有原始选项添加回来)

HTML

<select id="Current-Tier" onchange="removetier();" class="form-control boosting-select">
        <option value="100">Bronze</option>
        <option value="200">Silver</option>
        <option value="300">Gold</option>
        <option value="400">Platinum</option>
        <option value="500">Diamond</option>
</select>

<select id="Desired-Tier" class="form-control boosting-select">
        <option value="100">Bronze</option>
        <option value="200">Silver</option>
        <option value="300">Gold</option>
        <option value="400">Platinum</option>
        <option value="500">Diamond</option>
</select>

JS

 function removetier(){

     var currentTierValue = document.getElementById("Current-Tier");
     var current = currentTierValue.options[currentTierValue.selectedIndex].value;

     var desiredDivisionValue = document.getElementById("Desired-Tier");
     for(var i=0;i<desiredDivisionValue.length;i++){
         if(desiredDivisionValue[i].value < current){
             desiredDivisionValue.remove(desiredDivisionValue[i]);

         }
     }

     Update_Desired_Rank_image();

 }

2 个答案:

答案 0 :(得分:1)

您是否考虑过添加hidden属性而不是删除它们?

然后,下次收到请求时,您可以通过编程方式浏览列表并从每个选项中删除hidden属性。

hidden标签BTW的一个例子是

&#13;
&#13;
<select id="Desired-Tier" class="form-control boosting-select">
  <option value="100">Bronze</option>
  <option value="200">Silver</option>
  <option value="300">Gold</option>
  <option value="400">Platinum</option>
  <option value="500" hidden>Diamond</option>
</select>
&#13;
&#13;
&#13;

如果你运行它,你会看到Diamond被隐藏了。这样您就可以访问所有选项。

答案 1 :(得分:0)

您可以轻松迭代select输入,并将已删除的项目存储在数组中,或利用hidden标记上的option属性:

小提琴:https://jsfiddle.net/gLwwmh82/2/

HTML

    <select id="mySelect">
        <option value="">Select...</option>
        <option value="test1">Test1</option>
        <option value="test2">Test2</option>
        <option value="test3">Test3</option>
        <option value="test4">Test4</option>
        <option value="test5">Test5</option>
        <option value="test6">Test6</option>
    </select>

    <button id="btnRemove" onclick="remove()">Remove Half of Entries</button>
    <button id="btnReset" onclick="reset()">Reset</button>

JS

function reset() {
    var select = document.getElementById('mySelect');
    var options = select.querySelectorAll('option');
    for (var i = 0; i < options.length; i++) {
        options[i].removeAttribute('hidden');
    }
}

function remove() {
    var select = document.getElementById('mySelect');
    select.value = "";
    var entries = select.querySelectorAll('option');
    for (var i = 1; i < 5; i++) { 
        // Wrap the below line in your logic to know what to delete/not to delete
        entries[i].setAttribute('hidden', true);
    }
}