Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 276
Bhagirath Avatar asked May 21 '26 04:05

Bhagirath


1 Answers

You're overwriting the content of the same div that the checkbox lives in, using innerHTML like that. Use a second div, or use create element and append child instead of replacing the entire contents.

This works.

<html>
  <div id="test_div1">
  <input type="checkbox" name="test_checkbox" id="test_checkbox" onclick="check_test()"/>
  </div>
  <div id="test_div"></div>
  <script>
    function check_test() {
      if(document.contains(document.getElementById("test_number"))) {
        document.getElementById("test_number").remove();
      }
      document.getElementById("test_div").innerHTML += "<input type='number' name='test_number' id='test_number'/>";
    }
  </script>
</html>
like image 153
Nikki9696 Avatar answered May 22 '26 17:05

Nikki9696