0

I'm making a basic website that allows users to hide/show checkbox when a button is clicked. However, I need to click the button twice to get it to work. Any idea why?

function myFunction() {
  var check_box = document.getElementById('checkbox');
  if (check_box.style.display === "block") {
    check_box.style.display = "none";
  } else {
    check_box.style.display = "block";

  }
}
<button id="button" onclick="myFunction()">
Show/Hide Checkbox
</button>
<input type="checkbox" id="checkbox">
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 5
    The initial display value isn't "block" or "none". Use your debugger to see what the initial value is. –  Mar 10 '21 at 15:20
  • The `.style` object only shows styles that are directly coded onto the HTML elements. Default styles are not available. – Pointy Mar 10 '21 at 15:21
  • What Amy said above, therefore when you first click, it will *set it to `block`* – Rafalon Mar 10 '21 at 15:21
  • @Amy what is the default value for input? –  Mar 10 '21 at 15:22
  • may I suggest you use a CSS class that will use `display: none;` and toggle the class instead of the inline style – andy mccullough Mar 10 '21 at 15:22
  • 1
    There is no single default value unless you set it yourself. Use your debugger to see what the initial value is. –  Mar 10 '21 at 15:22
  • use `display !== "none"` for if condition .its will validate only element not hidden – prasanth Mar 10 '21 at 15:24
  • `` elements are "inline", but that will not be made evident by `.style.display`; it will be empty unless the element is explicitly styled in the HTML. – Pointy Mar 10 '21 at 15:24

0 Answers0