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 13:59

    If you are using JQuery, it goes as follows:

    Give an ID to your SELECT

    <select name="val" size="1" id="val">
    <option value="A">Apple</option>
    <option value="C">Cars</option>
    <option value="H">Honda</option>
    <option value="F">Fiat</option>
    <option value="I">Indigo</option>                    
    </select>
    
    $("#val option[value='A'],#val option[value='C']").remove();
    
    0 讨论(0)
  • 2020-12-05 14:00

    This should do it

    document.getElementsByName("val")[0].remove(0);
    document.getElementsByName("val")[0].remove(0);
    

    Check the fiddle here

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

    For clear all options en Important en FOR : remove(0) - Important: 0

    var select = document.getElementById("element_select");
    var length = select.length;
    for (i = 0; i < length; i++) {
         select.remove(0);
     //  or
     //  select.options[0] = null;
    } 
    
    0 讨论(0)
  • 2020-12-05 14:03

    Check the JQuery solution here

    $("#selectBox option[value='option1']").remove();
    
    0 讨论(0)
  • 2020-12-05 14:03

    A simple working solution using vanilla JavaScript:

    const valuesToRemove = ["value1", "value2"];
    
    valuesToRemove.forEach(value => {
        const mySelect = document.getElementById("my-select");
    
        const valueIndex = Array.from(mySelect.options).findIndex(option => option.value === value);
    
        if (valueIndex > 0) {
            mySelect.options.remove(valueIndex);
        }
    });
    
    0 讨论(0)
  • 提交回复
    热议问题