2012-02-26 157 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