How to remove/hide select options from select-list

前端 未结 11 2395
南笙
南笙 2021-02-20 07:53

I\'ve got a select list like this:


                        
    
提交评论

  • 2021-02-20 08:17

    You can "hide" the option by moving it to a hidden select element or cached document fragment, then move it back when you want to show it:

    var selectTool = (function() {
      var frag = document.createDocumentFragment();
      return {
        hideOpt: function (selectId, optIndex) {
          var sel = document.getElementById(selectId);
          var opt = sel && sel[optIndex];
          console.log(opt);
    
          if (opt) {
            frag.appendChild(opt);
          }
        },
    
        showOpt: function (selectId) {
          var sel = document.getElementById(selectId);
          var opt = frag.firstChild;
          if (sel && opt) {
            sel.appendChild(opt);
          }
        }
      }
    }());
    

    Then you can hide the 4th option like:

    <input type="button" value="Hide option" onclick="
      selectTool.hideOpt('selectlist',4);
    ">
    

    and show it again using:

    <input type="button" value="Show option" onclick="
      selectTool.showOpt('selectlist');
    ">
    

    All play code of course, but you should get some ideas. If you want to store many options, you'll need a way of referencing them so maybe store them in an object with some form of referencing scheme.

    0 讨论(0)
  • 2021-02-20 08:20

    Try to disable that option with disabled attribute.

    <select id="selectlist" name="selectproduct" >
     <option value=""> --- Select product  --- </option>
     <option value="1">Product 1</option>
     <option value="2">Product 2</option>
     <option value="3">Product 3</option>
     <option value="4" disabled="disabled">Product 4</option>
    </select>
    

    Check demo

    0 讨论(0)
  • 2021-02-20 08:20

    to append the child below the list of option using java script.

    `var option = document.createElement("option");
     option.text = "All Users";
     option.value = "all_user";
     var select = document.getElementById("log_user_type");
     select.appendChild(option);`
    
    0 讨论(0)
  • 2021-02-20 08:23

    if you want to remove some option from select list you can use this code:

    <script type="text/javascript">
        $(window).bind("load", function() {    
            $('#select_list_id option[value="AB"],option[value="SK"]').remove();
        });
    </script>
    
    0 讨论(0)
  • 提交回复
    热议问题