Search code examples
javascripthtmlradio-buttonselection

radio button switches upon submission


So when I select the radio button labeled black and click the add button to display the value, the radio button labeled red get selected and that value is displayed. Heres my code:

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>


Solution

  • When you do this in your code:

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

    You are actually setting the checked value to true, and not checking if it is true. Therefore you will have to change it to this:

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

    Then it should work.