2012-02-26 158 views
0

我在选择输入项目时遇到问题。从其他选择输入中删除所选项目

我想实现的是动态地从其他选择框中选择已经选择的选项,这样我就不能在多个框上选择相同的项目。问题是元素通过AJAX加载到数组中,我需要在选择输入后填充选项。这使得它变得更加困难。

总之 - 我怎样才能确保,如果我在选择选择一个项目,将在所有其它被删除,但是当我选择别的东西原来的项目将被再次等上显示...

我有一个小提琴为好,这是我在多大程度上得到:http://jsfiddle.net/P3j4L/

+0

我不确定在您的示例中这是否可行。如果您已经删除/禁用了其他选项,您将如何“选择其他内容”?这是我正在谈论的一个例子http://jsfiddle.net/BagKm/ :) – tftd 2012-02-26 18:34:12

+0

那是我害怕的事情,对我来说这似乎是不可能的,所以我去问你们。 – sed 2012-02-26 18:36:14

+0

对此问题的解决方法可能是从删除/禁用操作中排除第一个选择框。这样你就可以从某个地方选择所有的选项。当您从第一个选择框中选择一个选项时,请重新插入/重新启用其他选择框中除第一个选择框中所选选项之外的所有选项。如果我稍后再来,我可能会发布一个jsfiddle。 – tftd 2012-02-26 18:47:25

回答

3

你可以尝试这样的事情

function updateSelects() 
{ 
    $('.selectContainer .select').each(
    function (i, elem) 
    { 
     // Get the currently selected value of this select 
     var $selected = $(elem).find("option:selected"); 
     // Temp element for keeping options 
     var $opts = $("<div>"); 
     // Loop the elements array 
     for (i = 0; i < selectElements.length; i++) 
     { 
      var value = selectElements[i]; 
      // Check if the value has been selected in any select element 
      if ($selected.val() == value || !$('.select option[value=' + value + ']:selected').length) 
      { 
       // if not create an option and append to temp element 
       $opts.append('<option value="' + value + '">' + value + '</option>'); 
      } 
     } 
     // replace the html of select with new options 
     $(elem).html($opts.html()); 
     if ($selected.length) 
     { 
      // set the selected value if there is one 
      $(elem).val($selected.val()); 
     } 
     else 
     { 
      // new select element. So remove its selected option from all other selects 
      $('.selectContainer .select').not(this).find('option[value=' + $(elem).val() + ']').remove(); 
     } 
    } 
); 
} 

看到一个演示在这里:http://jsfiddle.net/P3j4L/1/

+0

这是纯粹的JavaScript可能吗?我受限于使用jQuery。 – fungusanthrax 2017-10-16 18:56:14