代码之家  ›  专栏  ›  技术社区  ›  AndrewC

javascript/jquery从select中删除或删除选项

  •  7
  • AndrewC  · 技术社区  · 14 年前

    基本上:

    if(mystatement == true)
    {
       //remove item with id 'option1' from select of id 'select1'
    }
    

    非常感谢。

    4 回复  |  直到 14 年前
        1
  •  7
  •   rahul    14 年前

    编辑

    $("#option1").remove();
    
        2
  •  14
  •   gnarf    14 年前

    按值删除:

    $("#select1 option[value=1]").remove();
    

    按文本删除:

    $("#select1 option:contains(Text)").remove();
    
        3
  •  3
  •   Andy E    14 年前

    jQuery查询:

    $("#option1").remove();
    

    $("#select").remove("#option1");
    

    以及经典的javascript方法:

    var option1 = document.getElementById("option1");
    document.getElementById("select1").removeChild(option1);
    
        4
  •  0
  •   Rafael    9 年前

    我见过很多人有这个问题。我已经创建了这个脚本,可能是有用的。希望您喜欢:

    var robable = {
      init: function() {
        robable.get_selected_option_from_select();
      },
      get_selected_option_from_select: function() {
        $(".robable").off().on("change", function() {
          if ($(this).val() !== "") {
            robable.add_to_list($(this));
          }
        });
      },
      remove_option_from_select: function(select_id, value) {
        $("#" + select_id + " option[value='" + value + "']").remove();
      },
      add_option_to_select: function(select_id, value, text) {
        $('#' + select_id).append('<option value="' + value + '">' + text + '</option>');
      },
      add_to_list: function(select) {
    
        option_text = $(".robable option[value='" + select.val() + "']").text();
    
        //Add to list
        $('#list').append("<li data-value='" + select.val() + "' data-text='" + option_text + "'><a href='#' class='filter-remove' data-parent-id='" + select.attr("id") + "'>Delete</a> " + option_text + "</li>");
        robable.remove_from_list();
    
        //Remove from select
        robable.remove_option_from_select(select.attr("id"), select.val());
      },
      remove_from_list: function() {
        $(".filter-remove").off().on("click", function() {
          var select_id = $(this).data('parent-id');
          var option_value = $(this).closest("li").data('value');
          var option_text = $(this).closest("li").data('text');
    
          //Add to select
          robable.add_option_to_select(select_id, option_value, option_text);
    
          //Remove from list
          $(this).closest("li").remove();
        });
      }
    };
    
    robable.init();
    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Select Robables</title>
    </head>
    
    <body>
      <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    
      <ul id="list"></ul>
    
    </body>
    
    </html>