Remove values from select list based on condition

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

I have the following in the page


                        
    
提交评论

  • 2020-12-05 13:50

    You have to go to its parent and remove it from there in javascript.

    "Javascript won't let an element commit suicide, but it does permit infanticide"..:)

    try this,

     var element=document.getElementsByName(val))
     element.parentNode.removeChild(element.options[0]); // to remove first option
    
    0 讨论(0)
  • 2020-12-05 13:53

    Removing an option

    $("#val option[value='A']").remove();
    
    0 讨论(0)
  • 2020-12-05 13:56

    Give an id for the select object like this:

    <select id="mySelect" name="val" size="1" >
        <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> 
    

    You can do it in pure JavaScript:

    var selectobject = document.getElementById("mySelect");
    for (var i=0; i<selectobject.length; i++) {
        if (selectobject.options[i].value == 'A')
            selectobject.remove(i);
    }
    

    But - as the other answers suggest - it's a lot easier to use jQuery or some other JS library.

    0 讨论(0)
  • 2020-12-05 13:56

    Alternatively you can also accomplish this with getElementsByName

    <select id="mySelect" name="val" size="1" >
    <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> 
    

    So in matching on the option value of "C" we could remove Cars from the list.

    var selectobject = document.getElementsByName('val')[0];
    for (var i=0; i<selectobject.length; i++){
    if (selectobject.options[i].value == 'C' )
        selectobject.remove(i);
      }
    
    0 讨论(0)
  • 2020-12-05 13:56

    The best answer is this

    function f1(){
      var r=document.getElementById('ms');
      for(i=0;i<r.length;i++)
        if(r.options[i].selected==true)
        {
          r.remove(i);
          i--;
        }
    }
    <select id="ms" size="5" multiple="multiple">
    <option>A</option>
    <option>B</option>
    <option>C</option>
    <option>D</option>
    <option>E</option>
    <option>F</option>
    </select>
    <input type="button" value="btn1" id="b1" onclick="f1()"/>

    Because your visitor can also add custom options as he want and delete them without need any info about his options . This code is the most responsive delete code that you can write as your selected delete..

    enjoy it:))))

    0 讨论(0)
  • 提交回复
    热议问题