我们想要创建一个表单,当在选择框中选择一个选项时,选项会在另一个选择框中更改,具体取决于所选择的选项。
示例:
Select box 1
Option A
Option B
Select box 2
Options change depending on if A or B is chosen
我们怎样才能做到这一点?
答案 0 :(得分:1)
有两种方法,具体取决于你是否希望通过Ajax调用第二个选择框中的选项,或者是否有两种可能性。
<强> HTML 强>
<select id="select1">
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="select2a" style="display:none;">
<!-- options -->
</select>
<select id="select2b" style="display:none;">
<!-- options -->
</select>
<强>的jQuery 强>
$('#select1').change(function(){
if($(this).val() == "a"){
$('#select2a').show();
$('#select2b').hide();
}elseif($(this).val() == "b"){
$('#select2a').hide();
$('#select2b').show();
}
});
如果您不想使用两个单独的选择框,则可以将选项存储在变量中,并根据第一个选择框中选择的选项更改选择框的.html()
。
答案 1 :(得分:0)
来自jQuery文档:
http://api.jquery.com/selected-selector/
$("select").change(function () {
var str = "";
//example from the docs - put code here which is specific to your use case.
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.trigger('change');
答案 2 :(得分:0)
这是一篇简短的博客文章,用select input和jQuery描述和实现一些条件逻辑: