【问题标题】:Prevent Multiple Selections of Same Value防止多个选择相同的值
【发布时间】:2011-04-29 10:40:13
【问题描述】:

我正在做一个项目,我有一个表单,该表单将具有多个“选择”输入,所有输入都具有相同的选项集。我想使用 jquery 禁用/隐藏其余“选择”输入中的选项,如果它已被选中。

例如:

<select id="1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
</select>

<select id="2">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
</select>

用户在第一次选择时选择“沃尔沃”。我希望它从第二个选择中删除。

任何信息将不胜感激。

【问题讨论】:

  • 请问你最后用了哪个答案?
  • @netadictos - 你的最终效果最好,但它仍然不是我想要的。我决定改用 Jquery UI 来制作可拖动的表单值。不过感谢您的帮助:)
  • Jquery UI 始终是一种非常现代的做事方式,我喜欢。至少我认为这是解决问题的方法;-)
  • @netadictos - 确实 :) 再次感谢

标签: jquery html forms select


【解决方案1】:

这里有继续选择和禁用我们想要的所有时间的代码。

首先是启用每个选项,然后查看所选值,然后禁用与所选值一致的选项。

这两个步骤至关重要,因为如果您再次选择,之前的禁用值将继续禁用。

最新版本

更优雅的方式,我们使用 map() (in stackoverflow there is a good explanation about this method) 和 filter() jquery 函数来完成这项工作。行数更少,我认为性能相同或更好。

http://www.jsfiddle.net/dactivo/keDDr/

$("select").change(function()
 {

        $("select option").attr("disabled",""); //enable everything

     //collect the values from selected;
     var  arr = $.map
     (
        $("select option:selected"), function(n)
         {
              return n.value;
          }
      );

    //disable elements
    $("select option").filter(function()
    {

        return $.inArray($(this).val(),arr)>-1; //if value is in the array of selected values
     }).attr("disabled","disabled");   

});

新版本

我已经编辑了我的答案,这是我的最终版本:

http://www.jsfiddle.net/dactivo/kNbWc/

$("select").change(function()
                   {

        $("select option").attr("disabled",""); //enable everything
        DisableOptions(); //disable selected values

                   });


function DisableOptions()
{
    var arr=[];
      $("select option:selected").each(function()
              {
                  arr.push($(this).val());
              });

    $("select option").filter(function()
        {

              return $.inArray($(this).val(),arr)>-1;
   }).attr("disabled","disabled");   

}

旧版本

http://www.jsfiddle.net/AyxL3/

$("select").change(function()
                   {

        $("select option").attr("disabled",""); //enable everything
        DisableOptions(); //disable selected values

                   });


function DisableOptions()
{

    $("select option").filter(function()
        {
              var bSuccess=false; //will be our flag to know it coincides with selected value
              var selectedEl=$(this);
              $("select option:selected").each(function()
              {

                  if($(this).val()==selectedEl.val())
                  {
                       bSuccess=true; //it coincides we will return true;
                       return false; // this serves to break the each loop
                   }               

              });
              return bSuccess;
   }).attr("disabled","disabled");   

}

【讨论】:

  • 在“新版本”上,当我在第一个选择中选择一个选项时,在第二个选择中禁用 2。在“最新”上,它不会禁用任何一个。
  • 我发现除了启用所有字段的第一行之外,这基本上是有效的。对于 2014 年使用 Chrome 的我来说,这只是导致所有字段在单击任何下拉列表后立即全部禁用。以下为我修复: $("#import_to_acf_matchoptions select option").prop("disabled", false);//启用一切
  • 谢谢@AdamJones 我一直在尝试解决这个问题,只是想阅读 cmets。我仍然无法重新启用未选择的东西,但至少它没有像以前那样禁用所有东西。
  • 由于某种原因,每次我选择某个值时,这里的所有方法都会为我禁用所有值。
【解决方案2】:

隐藏它们,请使用以下方法(因为 IE 错误阻止在 OPTION 上使用 CSS“显示”属性设置为“无”):

-将原始选项列表存储在数组中

-具有从数组构建选择#x的功能,滑动先前选择的项目

-为所有选择分配一个 onchange 处理程序,该处理程序将遍历所有以后的选择并调用此函数。

var option_value_order = {'volvo', 'saab', 'mercedes'};
var option_display_strings = new Array();
option_display_strings['volvo'] = 'Volvo'; 
//...

// Assume each of the selects' ID value is "select_1", "select_2" instead of "1", "2"
function redraw(selectNum) {
    var selectId = "select_" + selectNum;
    var s = document.getElementById(selectId);
    s.options.length = 0; // empty out
    var next = 0;
    for (var i = 0; i < option_value_order.length; i++) { 
        var skip = 0;
        for (var select_index = 0; select_index < selectNum; select_index++) {
            if (document.getElementById("select_"+select_index).selected == i)
                skip = 1;
            if (skip == 0) {
                var o = option_value_order[i];
                s.options[next] = o;
                // Don't recall how to set value different from option display, 
                // using option_display_strings[o] 
                next++;
            }
        }
    }
}

var total_selects = 2;

function change_later_selects(s) {
    var select_num = find_number(s.id); "this returns number 2 for "select_2" - homework
    for (var i = select_num + 1; i <= total_selects; i++) {
        redraw(i);
    }
}

然后是 HTML

<select id="select_2" onchange="change_later_selects(this);">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
</select>

【讨论】:

  • 这是 VANILLA JavaScript 对 jQuery 问题的回应吗?! +1 先生。
  • 但是为什么不把onchange事件也移到JS呢?
  • 我复制了这个例子,但我无法让它工作。我最终会有大约 14-16 个选择标签。
【解决方案3】:

这是一个工作示例:

http://jsfiddle.net/aNxBy/

使用您的数据,您必须这样做:

$(document).ready(function() {
    $('select').change(function() {
        $('option[value=' + $(this).val() + ']').attr('disabled', 'disabled');
    });
});

但是请注意,在您将其更改为另一个值后,这不会禁用禁用。我没有在此处添加此内容,因为您没有明确指定您在禁用该选项后需要做什么...实际上可能有多种情况。

您可以做的一件事是在更改事件触发时循环遍历所有相关的select 元素,找到所有选定选项的值,并在适当的情况下禁用。

【讨论】:

  • 我将如何禁用“禁用”?说如果用户改变了他们选择的值的想法?
  • 如何将其添加到代码中?我不是 jquery pro,但在弄清楚当前代码是如何应用“禁用”属性时仍然有点麻烦
  • 请看这个当你得到一个秒。我不太确定如何实现删除属性功能。我最终将使用大约 14-16 个选择标签。
【解决方案4】:

这个问题是搜索这个问题的答案的顶级谷歌结果,所以我会在这里发布一个更新的答案。这与 netadictos 的答案几乎完全相同,但适用于禁用和重新启用选择值并使用 prop 而不是 attr。经验证可在 Chrome 52 中运行。

    $("select").change(function()
    {
        $("select option").prop("disabled",""); //enable everything

        //collect the values from selected;
        var  arr = $.map
        (
            $("select option:selected"), function(n)
            {
                return n.value;
            }
        );

        //disable elements
        $("select option").filter(function()
        {
            return $.inArray($(this).val(),arr)>-1; //if value is in the array of selected values
        }).prop("disabled","disabled");

        //re-enable elements
        $("select option").filter(function()
        {
            return $.inArray($(this).val(),arr)==-1; //if value is not in the array of selected values
        }).prop("disabled","");
    }).trigger("change"); // Trigger the change function on page load. Useful if select values are pre-selected.

【讨论】:

    【解决方案5】:

    你可以做类似的事情

    var curSelected = $('#1 option:selected').val();
    $('#2 option[value="'+curSelected+'"]').remove()
    

    (当然,如果您打算通过change 处理程序将更改添加到选项本身,您可以直接使用$(this)

    当然这不会向后工作:)

    在这种情况下,我建议您直接使用 JavaScript 构建您的选项,以便您拥有完整的蓝图,在需要时从中删除元素,然后再将它们替换为各种 select

    【讨论】:

      【解决方案6】:
      $(document).ready(function() {
          $('#1').change(function() {
              $('option.hidden').removeClass('hidden')
              $('#2 option[value=' + $(this).val() + ']').addClass('hidden');
          });
          $('#2').change(function() {
              $('option.hidden').removeClass('hidden')
              $('#1 option[value=' + $(this).val() + ']').addClass('hidden');
          });
      });

      确保你有css

      .hidden {display:none}

      【讨论】:

      • 如果您再选择一次,这将不会重置之前选择的选项。
      【解决方案7】:

      看看this。它:

      1. 获取您刚刚更改的下拉列表的 ID
      2. 循环遍历所有选择列表
      3. 从所有其他列表中删除您刚刚选择的项目

      【讨论】:

      • 抱歉,添加了几个额外的字符。固定。
      • 如果您再选择一次,这将不会重置之前选择的选项。它使消失,而不是禁用。
      • 我怎样才能让他们重置?
      • 您可以执行.css('disabled','disabled') 并在值更改时重新启用它们,或者您可以将值存储在数组中并创建/删除它们。
      猜你喜欢
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多