我试图根据在是/否单选按钮上选择的答案显示或隐藏字段集。我有多个表单元素,必须根据相应的YES / NO单选按钮显示或隐藏。但是下面的代码对我不起作用。有人可以帮我纠正这个问题吗?
<!-- 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();
}
})
});
答案 0 :(得分:4)
你正在检查value属性的长度,1
(因为它们有valeus 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
答案 1 :(得分:1)
试试这个
$(document).ready(function(){
$(".subQuestion").hide();
$('#question input[type="radio"]').click(function(){
if (this.value == 1){
$(".subQuestion").show();
} else {
$(".subQuestion").hide();
}
})
});
答案 2 :(得分:0)
前面不需要$
,使用this.value
...并检查值本身而不是其长度......
此
if ($(this.value).length > 0){
应该是
if (this.value > 0){ //using DOM check if value is greter than 0
或
if ($(this).val()> 0){ //using jquery
所以您的最终代码应为
$(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();
}
})
});
答案 3 :(得分:0)
试试这个
$(document).ready(function(){
$(".subQuestion").hide();
$(document).on('click', '.myradio' , function() {
if (this.value == 0){
$(".subQuestion").hide();
}
else {
$(".subQuestion").show();
}
})
});
答案 4 :(得分:0)
试试this
,这对您有所帮助。在$(this.value).length > 0)
这行中的代码问题中,这是语法错误,难以匹配单击的单选按钮的值。
$(".subQuestion").hide();
$('input[type=radio]').change(function() {
if ($(this).val()== 0){
$(".subQuestion").show();
}
else {
$(".subQuestion").hide();
}
});