防止多次选择相同值

发布于 2024-09-28 20:14:06 字数 583 浏览 4 评论 0原文

我正在开发一个项目,其中有一个表单,该表单将具有多个“选择”输入,所有输入都具有相同的选项集。我想使用 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”。我希望将其从第二个选择中删除。

任何信息将不胜感激。

I am working on a project where I have a form that will have multiple 'select' inputs, all with the same set of options. I would like to use jquery to disable/hide an option in the rest of the 'select' inputs, if it has already been selected.

For example:

<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>

The user chooses 'Volvo' on the first select. I would like it removed from the second select.

Any info would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

蓝海 2024-10-05 20:14:06

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

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

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

最新版本

更优雅的方式,我们使用map()(在 stackoverflow 中是关于此方法的一个很好的解释)和 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");   

}

Here there is the code to continue selecting and disabling all the times we want.

First thing is to enable every option, and then look at the selected values, and disable the options which coincides with the selected values.

These 2 steps are crucial because if you select again, the disabled values of before would continue disabled.

NEWEST VERSION

The more elegant way, where we use map() (in stackoverflow there is a good explanation about this method) and filter() jquery functions to do the job. Less lines, and I think same performance or better.

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

});

NEW VERSION

I have edited my answer, this is my final version:

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

}
避讳 2024-10-05 20:14:06

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

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

- 有一个函数从数组构建 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>

To hide them, use the following approach (since IE bug prevents using CSS "display" property setting to "none" on an OPTION):

-Store the original list of options in an array

-Have a function to build the select #x from an array, slipping previously selected items

-Assign an onchange handler for all selects which loops through all later selects and calls this function.

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

And then the 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>
孤蝉 2024-10-05 20:14:06

这是一个工作示例:

http://jsfiddle.net/aNxBy/

对于您的数据,您必须执行此操作:

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

但是请注意,在将其更改为另一个值后,这不会禁用禁用功能。我没有在此处添加此内容,因为您没有具体指定禁用该选项后需要执行的操作...实际上可能有多种可能的情况。

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

Here's a working example:

http://jsfiddle.net/aNxBy/

With your data, you have to do this:

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

Be mindful, however, of the fact that this won't disable the disable after you've changed it to another value. I didn't add this in here because you didn't specify exactly what you needed to do after you disabled the option...really it could be a number of possible scenarios.

One thing you could do is to cycle through all relevant select elements when the change event fires, find the values of all the selected options, and disable where appropriate.

不如归去 2024-10-05 20:14:06

这个问题是搜索此问题答案的最佳谷歌结果,因此我将在这里发布更新的答案。这与 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.

This question was the top google result for searching for an answer to this, so I'll post an updated answer here. This is almost the exact same as netadictos's answer, but works for disabling and re-enabling the select values and uses prop instead of attr. Verified working in 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.
神经大条 2024-10-05 20:14:06

你可以做类似的事情

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

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

当然这会赢不能向后工作:)

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

you could do something like

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

(of course you could directly use $(this) if you plan to add the change to the options itself through the change handler)

Of course this won't work backwards :)

In that case I suggest you to build your options directly with JavaScript so that you have the complete blueprint from which remove elements when needed, before substituting them to various select

枯寂 2024-10-05 20:14:06
$(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}

$(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');
    });
});

Make sure you have in css

.hidden {display:none}

魄砕の薆 2024-10-05 20:14:06

看看这个。它:

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

Take a look at this. It:

  1. gets the ID of the dropdown you just changed
  2. loops through all the select lists
  3. delete the item you just selected from all the other lists
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文