![](/img/trans.png)
[英]jQuery Click Function: Show Div Based on Previous Radio Button Selection
[英]Using jquery to enable div on a page based on a radio button selection
如果使用 jquery 从单选按钮中选择是或否,我希望能够启用 div。 默认是页面加载时不显示 div。 当您现在 select 一个单选按钮时,它会确定显示哪个 div。
html 代码如下所示
<html>
<head>Testing</head>
<body>
<p>Are you 70 years and older? <input type="radio" value="yes" name="myradiobutton" /> Yes <input type="radio" value="no" name="myradiobutton" /> No</p>
<div style="display: none" id="yes">
<p>Yes was selected</p>
</div>
<div style="display: none" id="no">
<p>No was selected</p>
</div>
</body>
</html>
我做了很长时间 jquery 但想知道如何使用下面的 jquery 打开和关闭它。 我怎样才能写这个,以便我能够通过 jquery 控制每个 div 上的 styles(根据单选按钮选择打开和关闭它)?
$(".myradiobutton").click(function(){
var selectedval = $("#myradiobutton input[type='radio']:checked").val();
if(selectedval == "yes"){
//show the yes div
}
if(selectedval == "no"){
//show the no div
}
});
Id 必须是唯一的..您只能将它用于一个元素..您可以将相同的 class 用于divs
,因此您可以将它们都隐藏在一个选择中..您也可以使用这样的代码而不是使用 if声明..我更喜欢使用change
事件而不是click
收音机,复选框,select
$("[name='myradiobutton']").on('change', function(){ var selectedval = $("input[type='radio'][name='myradiobutton']:checked").val(); $('.just_test').hide(0).filter('#'+selectedval).show(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>Are you 70 years and older? <input type="radio" value="yes" name="myradiobutton" /> Yes <input type="radio" value="no" name="myradiobutton" /> No</p> <div style="display: none" class="just_test" id="yes"> <p>Yes was selected</p> </div> <div style="display: none" class="just_test" id="no"> <p>No was selected</p> </div>
不要忘记在 html 的divs
中添加class="just_test"
您尝试使用#myradiobutton
作为查询选择器,但#
表示您的 HTML 代码中没有的元素的id
属性。
要修复它,您不能让两个<input type="radio">
元素都使用myradiobutton
作为id
。
取而代之的是,我的建议是使用<label>
来表示<input>
s。
下面的例子:
<input type="radio" name="age" value="yes" id="older-than-70">
<label for="older-than-70">Yes</label>
<input type="radio" name="age" value="no" id="younger-than-70">
<label for="younger-than-70">No</label>
<input>
元素使用属性id
来标识自己,并使用属性name="age"
与其他<input>
进行分组。<label>
元素使用属性for
作为指向具有匹配id
的<input>
的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.