2013-01-09 71 views
0

我使用jQuery。如何過濾動態組合框?

$('#ranges').on('change', '.combo', function() { 
     var selectedValue = $(this).val(); 
     var s = $(this).parent("div").attr("class"); 
     if ($(this).find('option').size() > 2) { 
      var newComboBox = $(this).clone(); 
      var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10); 
      var newComboBoxIndex = thisComboBoxIndex + 1; 

     $('div.'+s+' .parentCombo' + thisComboBoxIndex).remove(); 

     if (selectedValue !== '') { 
      newComboBox.attr('data-index', newComboBoxIndex); 
      newComboBox.attr('id', 'combo' + newComboBoxIndex); 
      newComboBox.addClass('parentCombo' + thisComboBoxIndex); 
      newComboBox.find('option[val="' + selectedValue + '"]').remove(); 
      $('div.'+s).append(newComboBox); 
     } 

});

fiddle

我怎樣才能garantee該值前總是比下一個更高?可能會提醒用戶該問題或將該combobox_text_value設置爲「紅色」或阻止用戶提交。

在小提琴例如。如果我在第一個組合中選擇2,我應該只在下一個中選擇3。

ps:注意我,如果你需要更多的代碼。

動態組合框與值

回答

0

處理請參見工作的jsfiddle:

http://jsfiddle.net/JaVVe/22/

$('body').on('change', '.combo', function() { 
    var selectedValue = $(this).val(); 

    if ($(this).find('option').size() > 2) { 
     var $newComboBox = $(this).clone(); 
     var thisComboBoxIndex = parseInt($(this).data('index'), 10); 
     var newComboBoxIndex = thisComboBoxIndex + 1; 

     $('.parentCombo' + thisComboBoxIndex).remove(); 

     if (selectedValue !== '') { 
      $newComboBox.data('index', newComboBoxIndex) 
         .attr('id', 'combo' + newComboBoxIndex) 
         .addClass('parentCombo' + thisComboBoxIndex) 
         .find('option') 
      .filter(function(){return this.value<=selectedValue && this.value}).remove(); 
      if($('option',$newComboBox).size() > 1) 
       $('body').append($newComboBox); 
     } 
    } 

}); 
+0

感謝答覆。你爲什麼改變這個'$ newComboBox'? – pleaseDeleteMe

+0

它只是一個很好的做法,把$放在變量的前面引用jquery對象。這樣,每次你看到一個以$開頭的變量,你就知道你可以應用jquery方法。 –

+0

我正在使用你的方法,但是當我使用組合框進行處理時,comboindex總是相同並且正在造成麻煩 – pleaseDeleteMe