2013-01-09 141 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