我想创建一个包含year和make的下拉列表 如果客户选择年份中的每个选项,他们将获得同一类的make选项 例如:如果他们选择year = 2015(value = 65399),make的下拉列表将创建一个class =“65399”的列表 它不适用于我的代码
<!doctype html>
<html>
<head>
<title>Learning jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<form>
<select class="mn-year form-select" id="edit-mn-year" name="mn-year">
<option value="" selected="selected">- Choose Year -</option>
<option value="65399">2015</option>
<option value="56040">2014</option>
<option value="55580">2013</option>
<option value="55572">2012</option>
</select>
<select class="mn-make form-select" id="edit-mn-make" name="mn-make">
<option value="" selected="selected">- Choose Make -</option>
<option class="65399" value="65417">Chevrolet</option>
<option class="65399" value="65493">Ford</option>
<option class="65399" value="65403">GMC</option>
<option class="65399" value="65472">Jeep</option>
<option class="65399" value="65889">Ram</option>
<option class="65399" value="65488">Scion</option>
<option class="65399" value="65516">Toyota</option>
<option class="56040" value="63128">Chevrolet</option>
<option class="56040" value="65140">Ford</option>
<option class="56040" value="63121">GMC</option>
</select>
</form>
<script>
$(document).ready(function() {
var year = $("#edit-mn-make").children('option').map(function() {
return {
"value": this.value,
}
})
var make = $("#edit-mn-make").children('option').map(function() {
return {
"value": this.value,
"class": this.class,
"option": "<option value='" + this.value+ "'>" + this.text + "</option>"
}
})
$("#edit-mn-year").change(function() {
$("#edit-mn-make").children('option').remove();
var addoptarr = [];
for (i = 0; i < year.length; i++) {
for(j = 0; j< make.length; j++){
if ( year[i].value == make[j].class) {
addoptarr.push(make[i].option);
}
}
}
$("#edit-mn-make").html(addoptarr.join(''))
}).change();
})
</script>
</body>
</html>
答案 0 :(得分:1)
我相信你有点过分复杂了。我为你做了一个工作小提琴:https://jsfiddle.net/79o6w2nh/
我的实现只隐藏所有内容,然后显示将年份作为数据属性的选项。:
$("#edit-mn-year").change(function(){
$("#edit-mn-make").children().hide();
$("#edit-mn-make").children('*[data-year="'+$(this).val()+'"]').show();
});
答案 1 :(得分:0)
$(document).ready(function() {
$("#edit-mn-year").change(function(){
var cls=$(this).val();
$("#edit-mn-make ."+cls).attr('selected','selected');
});
});