问题描述
我正在尝试根据重力形式中单选按钮字段中的输入显示/隐藏div。我使用jQuery here找到了一个答案,该答案非常适合复选框,但是,当我尝试通过单选按钮执行相同操作时,它将做第一部分并隐藏选中的div,但不会显示取消选中单选按钮后,再次打开div。
这是我正在使用的jQuery:
jQuery(function ($) {
var trigger = $('#choice_13_1_0');
trigger.change(function(){
if ( $(this).is(":checked") ) {
jQuery(".conditional-display").hide();
} else {
jQuery(".conditional-display").show();
}
});
});
<ul class="gfield_radio" id="input_13_1">
<li class="gchoice_13_1_0">
<input name="input_1" type="radio" value="Option One" id="choice_13_1_0" tabindex="1">
<label for="choice_13_1_0" id="label_13_1_0">
Option One
</label>
</li>
<li class="gchoice_13_1_1">
<input name="input_1" type="radio" value="Option Two" id="choice_13_1_1" tabindex="2">
<label for="choice_13_1_1" id="label_13_1_1">
Option Two
</label>
</li>
<li class="gchoice_13_1_2">
<input name="input_1" type="radio" value="Option Three" id="choice_13_1_2" tabindex="3">
<label for="choice_13_1_2" id="label_13_1_2">
Option Three
</label>
</li>
我将这个div放在页面的其他位置:
<div class="conditional-display">
Content to conditionally display based on radio field selection
</div>
在此示例中,应该发生的情况是,在选择选项1时div将隐藏,然后在选择选项2或3时再次显示。
解决方法
假设您希望在单击第一个单选按钮时隐藏条件div
...
将事件处理程序按名称添加到单选按钮组中。然后使用带有条件的toggle来确定div是否可见。
jQuery(function ($) {
var trigger = $('[name=input_1]');
trigger.change(function(){
jQuery(".conditional-display").toggle(this.id !== "choice_13_1_0")
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="gfield_radio" id="input_13_1">
<li class="gchoice_13_1_0">
<input name="input_1" type="radio" value="Option One" id="choice_13_1_0" tabindex="1">
<label for="choice_13_1_0" id="label_13_1_0">
Option One
</label>
</li>
<li class="gchoice_13_1_1">
<input name="input_1" type="radio" value="Option Two" id="choice_13_1_1" tabindex="2">
<label for="choice_13_1_1" id="label_13_1_1">
Option Two
</label>
</li>
<li class="gchoice_13_1_2">
<input name="input_1" type="radio" value="Option Three" id="choice_13_1_2" tabindex="3">
<label for="choice_13_1_2" id="label_13_1_2">
Option Three
</label>
</li>
<div class="conditional-display">
Content to conditionally display based on radio field selection
</div>