防止多个相同值的选择

时间:2010-10-23 00:15:59

标签: jquery html forms select

我正在开发一个项目,我的表单中有多个'select'输入,所有输入都有相同的选项。我想使用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>

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

任何信息都将不胜感激。

7 个答案:

答案 0 :(得分:5)

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

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

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

最新版本

更优雅的方式,我们使用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");   

}

OLD VERSION

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");   

}

答案 1 :(得分:3)

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

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

- 具有从数组中构建select #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>

答案 2 :(得分:2)

这是一个有效的例子:

http://jsfiddle.net/aNxBy/

根据您的数据,您必须这样做:

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

但请注意,在将其更改为其他值后,禁用禁用这一事实。我没有在这里添加这个,因为你没有明确指出你需要做什么之后你禁用了这个选项......真的可能是一些可能的场景。

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

答案 3 :(得分:2)

此问题是搜索此答案的google搜索结果,因此我将在此处发布更新的答案。这几乎与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.

答案 4 :(得分:1)

你可以做点什么

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

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

当然这不会倒退:)

在这种情况下,我建议您直接使用JavaScript构建选项,以便在将其替换为各种select

之前,获得完整的蓝图,在需要时从中删除元素。

答案 5 :(得分:1)

看看this。它:

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

答案 6 :(得分:1)

$(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}

相关问题