Ryn9011
Ryn9011

Reputation: 179

else block in if statement is never reached

I know there are many similar questions on IF statements, but I haven't found one specific to my case

I can't see why the else block is never hit when the condition should be toggling between true and false

document.getElementById("outlineCheck").addEventListener("click",
  function() {
    if (document.getElementById("outlineCheck").checked == true) {
      document.getElementById("outlineCheck").checked = false;
    } else {
      console.log("hit")
      document.getElementById("outlineCheck").checked = true;
    }
  });
<label><input asp-for="CourseOfferingOverviewFlag" value="1" 
     id="outlineCheck" type="radio" />

Upvotes: 2

Views: 519

Answers (3)

V. Sambor
V. Sambor

Reputation: 13399

As @Barmar answer you are unchecking the checkbox all the time.

If you are trying to do something in checked or unchecked mode, I think you can do like this to have access to both conditions:

P.S. Try to cache your DOM access for better performance.

Example

var $checkbox = document.getElementById("outlineCheck");

$checkbox.addEventListener("click", function() {
  if ($checkbox.checked) {
    console.log('Now is checked')
  } else {
    console.log('And now is unchecked')
  }
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <input type="checkbox" id="outlineCheck">TEST
</body>

</html>

Upvotes: 1

Nemer
Nemer

Reputation: 687

if you need to use radio input you should have at least two inputs radio, for this reason, the first click will be true and not able to make it false, you should use checkbox instead. more info

Upvotes: 0

Barmar
Barmar

Reputation: 781721

It never gets to the else because you always undo what the user did.

The button is initially unchecked. When the user clicks on the button, it gets checked, so you go into the if block and uncheck the button. The next time the user clicks on the button, the same thing happens.

Upvotes: 2

Related Questions