jQuery依赖选择选项

我有一个大型数据库,我希望在第二个选择中显示选项,具体取决于使用jQuery的第一个选择的值。

我想在第一次选择时选择值为1的选项,在值为1的第二个selet选项中显示。

你能帮我举个例子吗?

首先选择

 Select City Manchester Leicester Londra  

第二个选择

  Select Street Street 1 Street 2 Street 3 Street 4 Street 5 Street 6 ..... Street 7 Street 8 Street 9  

这应该是直截了当的:

 $('#city').change(function(){ $('#street option') .hide() // hide all .filter('[value="'+$(this).val()+'"]') // filter options with required value .show(); // and show them }); 

考虑到urbz的评论,这对Milind Anantwar的回答几乎没有什么改进:

  • 现在代码选择所选城市的第一条街道
  • 如果城市选择元素重置没有街道
 $('#city').change(function() { $('#street option').hide(); $('#street option[value="' + $(this).val() + '"]').show(); // add this code to select 1'st of streets automaticaly // when city changed if ($('#street option[value="' + $(this).val() + '"]').length) { $('#street option[value="' + $(this).val() + '"]').first().prop('selected', true); } // in case if there's no corresponding street: // reset select element else { $('#street').val(''); }; }); 
    

这是工作DEMO

同步两个下拉列表与相同的类名称。

  

  

并使用一些JQuery。

 var $city = $(".city").on('change', function() { $city.not(this).get(0).selectedIndex = this.selectedIndex; }); 

试试这个:

 $('#city').change(function(){ $('#street option').hide(); $('#street option[value="'+$(this).val()+'"]').show() }); 

工作演示

http://jsfiddle.net/vikramjakkampudi/fuu94/88/

 $('#city').change(function(){ $('#street option[value!="'+$(this).val()+'"]').attr("disabled",true); 

});

其他选择

这是一项改进,只有在有数据的情况下才能激活街道选择

HTML:

   

JS:

 $( document ).ready(function() { $('#street').prop('disabled', true); }); $('#city').change(function() { $('#street option').hide(); $('#street option[value="' + $(this).val() + '"]').show(); // add this code to select 1'st of streets automaticaly // when city changed if ($('#street option[value="' + $(this).val() + '"]').length) { $('#street option[value="' + $(this).val() + '"]').first().prop('selected', true); $('#street').prop('disabled', false); } // in case if there's no corresponding street: // reset select element else { alert("B"); $('#street').val(''); $('#street').prop('disabled', true); }; });