我在这段代码中做错了什么:
<form action="">
<select class="input-xlarge required" id="inputGender" name="inputGender">
<option value="">select</option>
<option value="m">male</option>
<option value="w">female</option>
</select>
<select class="input-xlarge" id="inputWeight" name="inputWeight">
<option value="">select</option>
</select>
<input type="submit" name="action" value="Book" />
</form>
var data = [
[
{"ID":"1", "desc":"(12)"},
{"ID":"2", "desc":"(5)"},
{"ID":"6", "desc":"(15)"}
]
[
{"ID":"0", "desc":"(49)"},
{"ID":"7", "desc":"(5)"}
]
];
$("#inputGender").change((function() {
var $persons = $("#inputWeight").empty();
$.each(data[$(this).val() - 1], function() {
$persons.append("<option value=" + this.ID + ">" + this.desc + "</option>");
});
});
);
当选择值m
时,我想填充此数据:
[
{"ID":"1", "desc":"(12)"},
{"ID":"2", "desc":"(5)"},
{"ID":"6", "desc":"(15)"}
]
选择ID #inputWeight
。或者如果选择w
,则显示:
[
{"ID":"0", "desc":"(49)"},
{"ID":"7", "desc":"(5)"}
]
......但它没有用。
有些想法吗?
答案 0 :(得分:2)
这一行是你的JS中的错误:
$.each(data[$(this).val() - 1], function() {
在此上下文中, $this.val()
表示inputGender
的值,可以是“m”或“w”。您必须已从其他位置粘贴此代码,因为它采用整数值。尝试将数据更改为:
var data = {
m: [{"ID":"1","desc":"(12)"},{"ID":"2","desc":"(5)"},{"ID":"6","desc":"(15)"}],
w: [{"ID":"0","desc":"(49)"},{"ID":"7","desc":"(5)"}]
};
然后您可以使用$(this).val()
来获取所需的数组:
$("#inputGender").change(function() {
var $persons = $("#inputWeight").empty();
$.each(data[$(this).val()], function() {
$persons.append("<option value=" + this.ID + ">" + this.desc + "</option>");
});
});
在this fiddle中看到它正常工作。