2010-07-09 47 views
1

我設置了我的jQuery like so我想限制3個以上的選擇框只選一個<option>一次 - 我做錯了什麼?

它成功讓我在整個3個下拉菜單中只選擇一個選項。

但是,如果我刪除了一個下拉列表(使用方便的按鈕),則會永遠禁用某個選項(灰顯)。

你會明白我的意思。首先,確保它可以正常工作,並且不能多次選擇相同的選項。

現在,請移除並注意其中一個已被禁用,並且永遠不能再次被選中。

我不知道爲什麼它永遠灰掉我的選擇?它在製作selectedIndexes陣列時似乎一直在繼續。

有誰知道如何解決這個問題?

+0

我在所有三個下拉菜單中選擇'1'成功。 – Amarghosh 2010-07-09 05:52:26

+0

@Amarghosh你能爲我詳細闡述一下嗎?您是否禁用了JavaScript?更好的是,發佈一個答案,如果它有用,我會投票。乾杯。 – alex 2010-07-09 05:55:04

+0

@alex:刪除'console.log'一行,它在jsbin中拋出一個錯誤,並打破了javascript。我猜Amarghosh有同樣的問題。 – jAndy 2010-07-09 05:58:40

回答

3

我對你的代碼做了一些修改,你可以看到它們here。它在開始時也不適合我,但現在它按預期工作,我認爲。如果你有任何問題,只是評論:)


這裏,我們去:

重新聲明$selects陣列,一旦你刪除的元素。對元素的引用仍然在數組中,所以當你稍後計算選定的索引時,它仍然會在那裏!

select.next('button').click(function(event) { 
     event.preventDefault(); 

     select.remove(); 
     $(this).remove(); 
     $selects = $('select'); // <-- redeclare selects here, one is gone! 
}); 

在選擇單擊處理程序,使用nth-child代替eq。前者將選擇所有option,即他們父母的子女。而eq只會從匹配元素集合中選擇第i個元素(即它只會返回一個元素)。請注意,nth-child的索引是基於一個的。

// Remove them from this dropdown 
$.each(selectedIndexes, function(i, index) { 

    // use n-th child here to get the child of each select. 
    // eq only selects the element from the matched set 
    $thisSelect.find('option:nth-child('+(index+1)+')').attr("disabled","disabled"); 

}); 
+0

+1 Felix,很好的回答! – 2010-07-09 06:34:03

1

我相信你需要將代碼添加到該函數從選擇值的數組中刪除相關的值:

select.next('button').click(function(event) { 
     event.preventDefault(); 

     select.remove(); 
     $(this).remove(); 

    }); 

或者,你可以添加一個數組來跟蹤在下拉列表中選擇的值在刪除時將其刪除,然後從其他函數中排除這些值,其中您將使用的值變灰。

1

demo

這是因爲這條線的,var $selects = $('select');

是的,你刪除了select元素,但不是那var $selects

這會修復它...

select.remove(); 
    $(this).remove(); 
    $selects = $selects.not(select); 

這樣,

$(this).remove(); 
    $selects = $selects.not(select.remove()); 
1

好了,我要指出的是其他的答案沒有,你需要「回憶」你$select變量擁有最當前項目。然而,你的腳本失敗了,所以我採取了不同的方法。以下是我的代碼。您可以also demo it here和完整註釋版本is available here

var $selects = $('select'); 

$selects 
    .after('<button>remove</button><br /><br />') 
    .each(function(i, el) { 
    $(this) 
     .next() 
     .click(function(e) { 
     e.preventDefault(); 

     $(el).remove(); 
     $(this).remove(); 

     $selects = $('select'); 
     $selects.change(); 
     }); 
    }) 
    .change(function() { 
    $selects 
     .children().removeAttr("disabled").end() 
     .each(function(i, el){ 
     $selects 
      .not(this) 
      .find(':selected') 
      .each(function(){ 
      $(el).find('option') 
       .eq($(this).index()) 
       .attr('disabled', true); 
      });                
     }); 
    }) 
    .change(); 

+0

@alex肯定的事情!很高興我能幫上忙! – 2010-07-09 06:41:23

0

甚至去除選擇元件後$selects陣列包含引用。我修改$selects.each功能:

$selects.each(function() { 
     var select = $(this); 
     select.next('button').click(function(event) { 
     event.preventDefault(); 

     $selects=$selects.not(select);//ADDED THIS LINE 

     select.remove(); 
     $(this).remove(); 
    }); 
}); 
相關問題