【问题标题】:radio button switches upon submission单选按钮在提交时切换
【发布时间】:2019-04-13 20:08:18
【问题描述】:

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

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>

【问题讨论】:

    标签: button selection radio


    【解决方案1】:

    当您在代码中执行此操作时:

    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};
    

    那么它应该可以工作了。

    【讨论】:

    • 哇,谢谢!我以为我是这样尝试的,但显然我做错了什么感谢您的帮助,它现在可以正常工作了!
    猜你喜欢
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    相关资源
    最近更新 更多