单选按钮在提交时切换

时间:2018-11-10 13:40:11

标签: button selection radio

因此,当我选择标有黑色的单选按钮并单击“添加”按钮以显示该值时,标有红色的单选按钮将被选中并显示该值。这是我的代码:

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>

1 个答案:

答案 0 :(得分:0)

在代码中执行此操作时:

if(document.getElementById("btn").checked = true){
total = 0
}else if(document.getElementById("2ndbtn").checked = true){
    total = 1;
}else{total = 0};

您实际上是将检查值设置为true,而不是检查它是否为true。因此,您必须将其更改为此:

if(document.getElementById("btn").checked){
    total = 0
}else if(document.getElementById("2ndbtn").checked){
    total = 1;
}else{total = 0};

然后它应该工作。

相关问题