单选按钮在提交时切换
radio button switches upon submission
因此,当我 select 标记为黑色的单选按钮并单击添加按钮以显示该值时,标记为红色的单选按钮得到 selected 并显示该值。这是我的代码:
function add() {
var total;
if (document.getElementById("btn").checked = true) {
total = 0
} else if (document.getElementById("2ndbtn").checked = true) {
total = 1;
} else {
total = 0
};
document.getElementById("show").innerHTML = total;
}
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<h5>what color is the car?</h5>
<input type="radio" name="q1" value="0" id="btn" /> red
<input type="radio" name="q1" value="0" id="2ndbtn" /> black
<button type="button" onclick="add();">add</button>
<p id="show"></p>
<script src="questions.js"></script>
</body>
</html>
当您在代码中执行此操作时:
if(document.getElementById("btn").checked = true){
total = 0
}else if(document.getElementById("2ndbtn").checked = true){
total = 1;
}else{total = 0};
您实际上是将检查值设置为真,而不是检查是否为真。因此,您必须将其更改为:
if(document.getElementById("btn").checked){
total = 0
}else if(document.getElementById("2ndbtn").checked){
total = 1;
}else{total = 0};
那么应该可以了。
因此,当我 select 标记为黑色的单选按钮并单击添加按钮以显示该值时,标记为红色的单选按钮得到 selected 并显示该值。这是我的代码:
function add() {
var total;
if (document.getElementById("btn").checked = true) {
total = 0
} else if (document.getElementById("2ndbtn").checked = true) {
total = 1;
} else {
total = 0
};
document.getElementById("show").innerHTML = total;
}
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<h5>what color is the car?</h5>
<input type="radio" name="q1" value="0" id="btn" /> red
<input type="radio" name="q1" value="0" id="2ndbtn" /> black
<button type="button" onclick="add();">add</button>
<p id="show"></p>
<script src="questions.js"></script>
</body>
</html>
当您在代码中执行此操作时:
if(document.getElementById("btn").checked = true){
total = 0
}else if(document.getElementById("2ndbtn").checked = true){
total = 1;
}else{total = 0};
您实际上是将检查值设置为真,而不是检查是否为真。因此,您必须将其更改为:
if(document.getElementById("btn").checked){
total = 0
}else if(document.getElementById("2ndbtn").checked){
total = 1;
}else{total = 0};
那么应该可以了。