我有两份名单,
选择列表1包含移动电话品牌名称
<select name="mobile-phone" class="mobile-phone">
<option value="Select">Select</option>
<option value="Nokia">Nokia</option>
<option value="Samsung">Samsung</option>
<option value="HTC">HTC</option>
<option value="Apple">Apple</option>
</select>Select 2包含电话类型如下
<select name="mobile-model" class="mobile-model">
<option value="Select">Select</option>
<option value="Nokia--Lumia-520">Lumia 520</option>
<option value="Nokia--Lumia-620">Lumia 620</option>
<option value="Samsung--Galaxy-s3">Galaxy S3</option>
<option value="Samsung--Galaxy-s4">Galaxy S4</option>
<option value="HTC--hero">Hero</option>
<option value="HTC--one">One</option>
<option value="Apple--iphone4">iPhone 4</option>
<option value="Apple--iphone5">iPhone 5</option>
</select>我的要求是,我想显示选择列表2根据用户在选择列表1中选择的值。
如果用户在第一选择中选择,那么第二个选择列表中应该只显示Lumia手机。就像其他手机一样。
当None在第一个选择列表中被选中时,那么第二个选择列表不应该显示任何内容,但是没有任何选项仍然是可见的(比如禁用按钮)。
如何使用jQuery完成这一任务?
我从上面的选择列表中创建的JSFiddle。
发布于 2013-12-08 23:08:13
我想你是在找:
$("#sel2").prop("disabled", true);
$( "#sel1" ).change(function() {
var value = $(this).val();
$("#sel2").prop("disabled", false);
$("#sel2 > option").hide();
$("#sel2 > option[value*='" + value +"']").show();
});只有我把选择Id放在Jquery中,这样做就更容易了。在禁用任何选择的控件之前,当第一个选择只更改时,我保留使用option[value*='" + value +"']"的选项。
现场演示
发布于 2013-12-08 23:41:14
我建议:
/* select the select element whose name is "mobile-phone",
assign an event-handler for the 'change' event:
*/
$('select[name="mobile-phone"]').change(function () {
// get the relevant/selected brand-name:
var brand = this.value;
/* find the option elements inside of the select element with
name="mobile-model", enable them all:
*/
$('select[name="mobile-model"] option').prop('disabled', false)
// show them all:
.show()
// filter the collection, to find only those whose value does not start with the brand-name:
.filter(function () {
return !(this.value.indexOf(brand) === 0);
})
// disable those elements:
.prop('disabled', true)
// hide them:
.hide();
});JS Fiddle演示。
参考文献:
filter()。hide()。prop()。show()。发布于 2016-07-15 10:48:12
有一个jQuery插件可以很好地处理这种情况:http://www.appelsiini.net/projects/chained。
https://stackoverflow.com/questions/20459909
复制相似问题