Search code examples
javascripthtmlcheckboxinnerhtml

Checkbox not checked onclick JavaScript


I'm trying to add an input field on click of checkbox, and I want the checkbox to be checked (which is its default behaviour!), but the checkbox is not getting checked even after the input field appears. The following is my HTML code with JavaScript.

function check_test() {
  if (document.contains(document.getElementById("test_input"))) {
    document.getElementById("test_input").remove();
  }
  document.getElementById("test_div").innerHTML += "<input type='text' name='test_input' id='test_input'/>";
}
<div id="test_div">
  <input type="checkbox" name="test_checkbox" id="test_checkbox" onclick="check_test()" />
</div>

I also tried this in JsFiddle which gives the same error and am not sure what I'm doing wrong.

https://jsfiddle.net/1yLb70og/1/


Solution

  • You're conditionally removing the #test_input if it exists in the DOM, but then you're not using an else when adding it. So no matter which state you're in, you'll always end the function with having added the input to the DOM.

    As others have mentioned, when you += on the innerHTML, then you're actually creating a whole new string, thereby reinitializing your original checkbox to unchecked.

    You may want to just append a new child to the wrapper. I've also used the onchange event instead so that it will do what you want no matter if the box is checked by a click or programmatically.

    function check_test(checkbox) {
      const checked = checkbox.checked; // is it checked?
      const testInput = document.getElementById("test_input"); // test_input element
      
      // if it's checked and doesn't have an input, add it
      if (checked && !testInput) {
        const newInput = document.createElement('input');
        newInput.type = 'text';
        newInput.name = 'test_input';
        newInput.id = 'test_input';
        checkbox.parentNode.appendChild(newInput);
      }
      // otherwise, if it's not checked and there is an input in the DOM, remove it
      else if (!checked && testInput) {
        document.getElementById("test_input").remove();
      }
    }
    <div id="test_div">
      <input type="checkbox" name="test_checkbox" id="test_checkbox" onchange="check_test(event.target)" />
    </div>