如何使用jQuery根据单选按钮是否选中显示内容
我被某件事困住了。我有一个表单,其中的字段仅在选中特定单选按钮时显示。当有人第一次使用以下代码填写表单时,这很容易。
HTML
<fieldset id="question">
<legend>This is my question</legend>
<label for="answerYes">Yes</label>
<input name="answer" id="answerYes" type="radio" value="1" />
<label for="answerNo">No</label>
<input name="answer" id="answerNo" type="radio" value="0" />
</fieldset>
jQuery
$("#subQuestion").hide();
$("#answerYes").click(function() {
$("#subQuestion").show();
});
$("#answerNo").click(function() {
$("#subQuestion").hide();
});
当有人返回表单进行编辑时,此逻辑就会崩溃。在这种情况下,字段已预先填充,因此单击功能不存在。如果在页面加载时选中#answerYes,我如何使用 jQuery 显示#subQuestion。
I'm stuck on something. I have a form that has fields which only show when a particular radio button is checked. This is easy enough to when someone is filling out the form for the first time using the following code.
HTML
<fieldset id="question">
<legend>This is my question</legend>
<label for="answerYes">Yes</label>
<input name="answer" id="answerYes" type="radio" value="1" />
<label for="answerNo">No</label>
<input name="answer" id="answerNo" type="radio" value="0" />
</fieldset>
jQuery
$("#subQuestion").hide();
$("#answerYes").click(function() {
$("#subQuestion").show();
});
$("#answerNo").click(function() {
$("#subQuestion").hide();
});
This logic breaks down though when someone comes back to the form to edit it. In that case, the fields are prepopulated so the click function doesn't exist. How can I use jQuery to show #subQuestion if #answerYes is checked when the page loads.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试在页面中添加 $(document).ready() 处理程序...
一旦页面完全加载(并动态预填充值),该处理程序就会触发
Try adding a $(document).ready() handler to your page...
This handler will fire off once the page is completely loaded (and dynamically pre-populated with values)
将逻辑附加到
change()
事件*。此外,您可以使用:checked
选择器来获取当前选定的单选按钮。--
* 有些人报告了
更改
的问题,并改为使用
click()
来处理逻辑Attach the logic to the
change()
event*. Furthermore, you can use dthe:checked
selector to get the currently-selected radio button.--
* Some have reported isues with
change
, and have insteadused
click()
to handle the logic将所有渲染逻辑保留在单个函数中,并在文档返回时调用该函数:
Keep all the rendering logic in a single function, and call that function when the document comes back:
如果答案在服务器端,例如通过 PHP,那么您应该使用服务器端代码设置 #subQuestion 的样式:
...更好的是,分配一个类来处理是否显示 div。
If the answer is on the server side, like via PHP, then you should just set the style of #subQuestion using your server side code:
...better yet, assign a class that handles whether the div is shown or not.