[英]how to display text in a particular span style based on the radio button selection?
<html>
<head>
<script>
function check(){
var button =document.getElementsByName("rdName");
//rdName is the name of the radio buttons//
var style =document.getElementsByName("spans");
// spans is the name of the span tags included//
for(var i=0; i<button.length;i++){
if(button[i].checked == true){
document.getElementById(style[i].id).innerHTML ="YOU ARE:" + button[i].value;
}
}
}
</script>
</head>
<body>
<form id="myForm">
<center>
<input type="radio" id="radio1" name="rdName" onclick="check()" value="male"> male
<input type="radio" id="radio2" name="rdName" onclick="check()" value="female">female
// corresponding span tags for the radio buttons//
<span id="sp1" name="spans" style="background:red"></span>
<span id="sp2" name="spans" style="background:blue"></span>
</center>
</form>
</body>
</html>
这里我有 2 个按钮和 2 个 span 标签。 单击第一个按钮时,我想以第一个跨度样式显示文本。 选择了第二个按钮时,我需要在第二个跨度样式中显示文本。 此代码有效,但是当我在单击第一个单选按钮后单击选择第二个单选按钮时,我会在窗口中的不同跨度中获得两个文本。 我只想查看一次选择的单选按钮的特定跨度样式。
添加 else 条件将帮助您显示与单击单选按钮对应的跨度。 这是更新的代码。 希望能帮助到你!
if(button[i].checked == true){
document.getElementById(style[i].id).innerHTML ="YOU ARE:" + button[i].value;
}
// add this to your code.
else{
document.getElementById(style[i].id).innerHTML ="";
}
如果男性检查为真,则显示 YOU ARE : MALE,对于第二个跨度,将其设置为空字符串。 Incase 女性反之亦然。
您不需要 JavaScript,因为您可以在纯 CSS 中完成。 在 CSS 中,您可以使用:chekced
选择处于选中状态的输入。 您可以在初始加载时隐藏#sp1, #sp2
,然后根据选中的值显示。 在 CSS 中使用~
将选择任何兄弟姐妹(相邻或不相邻)。
#sp1, #sp2 { display: none; } input[value="male"]:checked~#sp1 { display: initial; } input[value="female"]:checked~#sp2 { display: initial; }
<form id="myForm"> <center> <input type="radio" id="radio1" name="rdName" value="male"> male <input type="radio" id="radio2" name="rdName" value="female">female // corresponding span tags for the radio buttons// <span id="sp1" name="spans" style="background:red">YOU ARE: male</span> <span id="sp2" name="spans" style="background:blue">YOU ARE: female</span> </center> </form>
Adding 2 lines inside for worked:
for(var i=0; i<button.length;i++){
document.getElementById(style[i].id).style.display = "none";
if(button[i].checked == true){
document.getElementById(style[i].id).style.display = "block";
document.getElementById(style[i].id).innerHTML ="YOU ARE:" + button[i].value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.