因此,当我加载页面时,我会从数据库检索信息,并根据其值检查单选按钮...
我需要最初显示文本框 - 基于已选中的单选按钮
当我执行点击事件时工作正常,但我需要在页面加载时显示文本框,因为第一个单选按钮是从数据库中检查的...
<p>
Show textboxes <input type="radio" name="radio1" value="Show" checked="checked">
Do nothing <input type="radio" name="radio1" value="Nothing">
</p>
Wonderful textboxes:
<div class="text"><p>Textbox #1 <input type="text" name="text1" id="text1" maxlength="30"></p></div>
<div class="text"><p>Textbox #2 <input type="text" name="text2" id="text2" maxlength="30"></p></div>
这是我的 FIDDLE - 演示 http://jsfiddle.net/rbla/5fq8q2bj/
这里是使用toggle的jquery
$(document).ready(function() {
$(".text").hide()
$('[name=radio1]').on('change', function(){
$('.text').toggle(this.value === 'Show');
}).trigger('change');
});
任何想法...
最佳答案
您的解决方案不起作用的原因是您正在检查所有 radio 输入,然后根据其值切换元素 - 无论是否选中。因此,在运行时,您的脚本将执行以下操作:
- 遇到第一个 radio 元素,触发
onchange
事件,触发onchange
回调,并显示.text
元素 - 遇到第二个 radio 元素,触发
onchange
事件,触发onchange
回调,并再次隐藏.text
元素
如果您将控制台日志放入回调中,您将意识到 .text
元素会快速连续地显示和隐藏。
您真正想做的只是在检查时执行切换。因此,您的示例只需在执行切换之前强制检查 this.checked
是否为真即可工作:
$('[name=radio1]').on('change', function() {
if (this.checked) {
$('.text').toggle(this.value === 'Show');
}
}).trigger('change');
请参阅下面的工作示例:
$(document).ready(function() {
$(".text").hide()
$('[name=radio1]').on('change', function() {
if (this.checked) {
$('.text').toggle(this.value === 'Show');
}
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Show textboxes
<input type="radio" name="radio1" value="Show" checked="checked"> Do nothing
<input type="radio" name="radio1" value="Nothing">
</p>
Wonderful textboxes:
<div class="text">
<p>Textbox #1
<input type="text" name="text1" id="text1" maxlength="30">
</p>
</div>
<div class="text">
<p>Textbox #2
<input type="text" name="text2" id="text2" maxlength="30">
</p>
</div>
关于javascript - 页面加载时根据单选按钮选择或值显示文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46850788/