我正在尝试根据“是/否”单选按钮上选择的答案来显示或隐藏字段集。我有多个表单元素,必须根据相应的“是/否”单选按钮显示或隐藏这些元素。但下面的代码对我不起作用。有人可以帮我解决这个问题吗?
<!-- My Form Element -->
<form>
<fieldset id="question">
<legend>This is my question</legend>
<label for="answerYes">Yes</label>
<input name="answer" class="myradio" type="radio" value="1" />
<label for="answerNo">No</label>
<input name="answer" class="myradio" type="radio" value="0" />
</fieldset>
<fieldset class="subQuestion">
<legend>This is my question</legend>
<label for="answerYes">Yes</label>
<input name="answer" class="subradio" type="radio" value="1" />
<label for="answerNo">No</label>
<input name="answer" class="subradio" type="radio" value="0" />
</fieldset>
</form>
// Jquery to show or hide subQuestion
$(document).ready(function(){
// do your checks of the radio buttons here and show/hide what you want to
$(".subQuestion").hide();
$(document).on('click', '.myradio' , function() {
if ($(this.value).length > 0){
$(".subQuestion").show();
}
else {
$(".subQuestion").hide();
}
})
});
最佳答案
您正在检查 value 属性的长度,即 1
(因为它们具有值 0
0 和 1
)情况下,您需要检查该值是否大于0
$(document).ready(function(){
// do your checks of the radio buttons here and show/hide what you want to
$(".subQuestion").hide();
$(document).on('click', '.myradio' , function() {
if (this.value > 0){
$(".subQuestion").show();
}
else {
$(".subQuestion").hide();
}
})
});
演示:Fiddle
关于jquery - 如何使用 jquery 显示或隐藏 div 或 form 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18778701/