【问题标题】:Jquery dynamic options remove/add in select formsJquery 动态选项在选择表单中删除/添加
【发布时间】:2013-12-04 19:35:53
【问题描述】:

我有以下简单的 Html 代码,其中包含 2 个具有相同选项值的 SELECT 表单:

<select id="first">
    <option value="none">None</option>
    <option value="one">Toyota</option>
    <option value="two">Nissan</option>
</select>

<select id="second">
    <option value="none">None</option>
    <option value="one">Toyota</option>
    <option value="two">Nissan</option>
</select>

我正在编写一个 jquery 脚本,它应该执行以下操作: 如果在#first 选择中我选择除“none”之外的任何值,f.e.丰田,它会自动从#second select中消失:

<select id="second">
    <option value="none">None</option>
    <option value="two">Nissan</option>
</select>

此外,如果我在 #second 选择中选择 Nissan(假设 #first 仍然选择了 Toyota),它应该会自动从 #first 选择中消失:

<select id="first">
    <option selected="selected" value="one">Toyota</option>
    <option value="none">None</option>
</select>

最后,当我在任何选择表单中将选择器重置为“无”时,它应该在同一位置的另一个选择中重新创建该选项。

如何更好地实现?使用 .remove()/.append() 操作还是 .hide()/.unhide() 更好?到目前为止,我创建了以下 sn-p:

$(document).on('change','select', function() {
   var sel = $(this).attr('id');
   var val = $(this).val();

if ( sel === "first" && val != "none") {
    $("#second option[value="+val+"]").remove();
} else if ( sel === "second" && val != "none") {
    $("#first option[value="+val+"]").remove();
}

这只是从另一个选择中删除选定的选项,但是在将选择更改为“无”后如何在同一位置正确地重新创建选项?

UPDATE:.hide()函数在某些浏览器中不起作用,我需要使用.remove()/.append(),但问题是如何追加到位置那是以前吗?

【问题讨论】:

    标签: jquery select


    【解决方案1】:

    这是另一种更动态的方法来做你想做的事。我认为这将是最好的选择。

    http://jsfiddle.net/rK7tJ/1/

    $("#first").change(function() {
        if($("#first").val() != "none") {
            $("#second option[value!="+$("#first").val()+"]").show();
            $("#second option[value="+$("#first").val()+"]").hide();
        } else {
            $("#second option[value!="+$("#first").val()+"]").show();
        }
        $("#second").val('none');
    });
    
    $("#second").change(function() {
        if($("#second").val() != "none") {
            $("#first option[value!="+$("#second").val()+"]").show();
            $("#first option[value="+$("#second").val()+"]").hide();
        } else {
            $("#first option[value!="+$("#second").val()+"]").show();
        }
        $("#first").val('none');
    });
    

    【讨论】:

    • 谢谢,太棒了!
    • 如果它解决了您的问题,您应该投票;)必须让他们得分!大声笑
    • 对了,我发现 .hide() 不适用于
    • Dang mac 用户 ;) 很容易切换到删除和重新创建它们
    • 我为stackoverflow.com/questions/20399968/…创建了新线程,欢迎您!
    【解决方案2】:

    删除一个选项后,您可以使用 .append 重新添加一个:

    $('#selectID').append($("<option></option>").attr("value","SomeVal").text("SomeText"));
    

    编辑:我认为这就是你想要做的对吗? http://jsfiddle.net/zdZ3d/

    $("#first").change(function() {
    switch($("#first").val()) {
        case "one":
            $("#second option[value='one']").hide();
            $("#second option[value!='one']").show();
            $("#second").val("none");
            break;
        case "two":
            $("#second option[value='two']").hide();
            $("#second option[value!='two']").show();
            $("#second").val("none");
            break;
        case "none":
            $("#second option[value='one']").show();
            $("#second option[value!='two']").show();
            $("#second").val("none");
            break;
    }
    });
    
    $("#second").change(function() {
    switch($("#second").val()) {
        case "one":
            $("#first option[value='one']").hide();
            $("#first option[value!='one']").show();
            $("#first").val("none");
            break;
        case "two":
            $("#first option[value='two']").hide();
            $("#first option[value!='two']").show();
            $("#first").val("none");
            break;
        case "none":
            $("#first option[value='one']").show();
            $("#first option[value!='two']").show();
            $("#first").val("none");
            break;
    }
    });
    

    【讨论】:

    • 另一个问题是,当我将所选选项的值保存到变量中时: var firstval = val;但是接下来当我选择无时,脚本会丢失设置的 firstval 值,我在控制台中看到它是未定义的。 if (sel === "first") { if (val === "none") { $("#second").append(' '); $("#third").append(''); } 其他 { var firstval = val; $("#second option[value="+val+"]").remove(); $("#第三个选项[value="+val+"]").remove(); }
    • 使用隐藏/显示在我的编辑中检查解决方案。它可以适应的不仅仅是现有的东西,只需为添加的选项添加一个新案例。
    【解决方案3】:

    jsFiddle

    只要您有办法将选择组合在一起,这将起作用。在这种情况下,我只是使用了一个类。此外,还有一种比硬编码更好的方法来设置每个选择的起点。将 prefText 设置为:jQuery(".onlySelectOnce:first").html() 可能会起作用。

    var prefArr = ["one", "two", "three"];
    var prefText = ['<option value="">None</option>',
    '<option value="one">Toyota</option>',
    '<option value="two">Nissan</option>',
    '<option value="three">Dodge</option>'];
    
    jQuery('#content').on("change","select[name^=pref]",function(){
            var selectedPrefs = [];
            //What items are selected
            jQuery("select[name^=pref]").each(function(){
                selectedPrefs.push(jQuery(this).val());
            });
            //make sure to add selection back to other selects
            jQuery("select[name^=pref]").each(function(i,select){
                jQuery(select).empty();
                jQuery(select).append(prefText);
                var elZero = selectedPrefs[i];
                jQuery(select).val(elZero);
                console.log(jQuery(select).prop("name")+" "+i+" "+elZero);
            });
            //remove already selected options
            jQuery("select[name^=pref]").each(function(i,select){
                jQuery("select[name^=pref] option").each(function(ii,option){
                    if(jQuery(option).val() != "" && selectedPrefs[i] == jQuery(option).val() && selectedPrefs[i] != jQuery(option).parent().val()){
                        jQuery(option).remove();
                    }
                });
            });
        });
    

    【讨论】:

      【解决方案4】:

      对于 N 个 SELECT 的情况如何(至于秘密问题)。如果您足够幸运,不必拘泥于必须支持 IE,您可以用 Hide & Show 代替 prop('disabled', true) 和 prop('disabled', false)。希望我能。

      var lastQuestion;
      $("select").bind('click keyup', function (event) {
          lastQuestion = $(event.srcElement).val();
      });
      
      $("select").bind('change', function (event) {
          $("select").not(event.srcElement).each(function (index) {
              if(lastQuestion != '')
                  $("#" + this.id + " option[value='" + lastQuestion + "']").prop('disabled', false);
              if ($(event.srcElement).val() != "") {
                  $("#" + this.id + " option[value='" + $(event.srcElement).val() + "']").prop('disabled', true);
              }
              //$("#" + this.id).val("");
          });
      });
      

      【讨论】:

        猜你喜欢
        • 2011-08-06
        • 1970-01-01
        • 2014-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多