Remove values from select list based on condition

后端 未结 18 2228
温柔的废话
温柔的废话 2020-12-05 13:15

I have the following in the page


                        
    
提交评论

  • 2020-12-05 14:06
    if(frm.product.value=="F"){
        var select = document.getElementsByName('val')[0];
        select.remove(0);
        select.remove(1);
    }
    
    0 讨论(0)
  • 2020-12-05 14:07

    To remove options in a select by value I would do (in pure JS) :

    [...document.getElementById('val').options]
        .filter(o => o.value === 'A' || o.value === 'C')
        .forEach(o => o.remove());
    
    0 讨论(0)
  • 2020-12-05 14:07

    A few caveats not covered in most answers:

    • Check against multiple items (some should be deleted, some should remain)
    • Skip the first option (-Select-) on some option lists

    A take on these:

    const eligibleOptions = ['800000002', '800000001'];
    let optionsList = document.querySelector("select#edit-salutation");
    for (let i = 1; i<optionsList.length; i++) {
        if(eligibleOptions.indexOf(optionsList.options[i].value) === -1) {
            cbxSal.remove(i);
            i--;
        }
    }
    
    0 讨论(0)
  • 2020-12-05 14:15

    with pure javascript

    var condition = true; // your condition
    if(condition) {
        var theSelect = document.getElementById('val');
        var options = theSelect.getElementsByTagName('OPTION');
        for(var i=0; i<options.length; i++) {
            if(options[i].innerHTML == 'Apple' || options[i].innerHTML == 'Cars') {
                theSelect.removeChild(options[i]);
                i--; // options have now less element, then decrease i
            }
        }
    }
    

    not tested with IE (if someone can confirm it...)

    0 讨论(0)
  • 2020-12-05 14:15

    As some mentioned the length of the select element decreases when removing an option. If you just want to remove one option this is not an issue but if you intend to remove several options you could get into problems. Some suggested to decrease the index manually when removing an option. In my opinion manually decreasing an index inside a for loop is not a good idea. This is why I would suggest a slightly different for loop where we iterate through all options from behind.

    var selectElement = document.getElementById("selectId");
    
    for (var i = selectElement.length - 1; i >= 0; i--){
      if (someCondition) {
        selectElement.remove(i);
      }
    }
    

    If you want to remove all options you can do something like this.

    var selectElement = document.getElementById("selectId");
    
    while (selectElement.length > 0) {
      selectElement.remove(0);
    }
    
    0 讨论(0)
  • 提交回复
    热议问题