Search code examples
javascripthtmlcheckboxtoggle

How to remove inner HTML content onchange


I created a form where a user selects options from a checkbox list. So when a user selects an option in the checkbox, I use a function to show the value of the input field using onchange within inner HTML. My question is, how do we remove that same inner HTML content if the user un-selects those options? So when the user toggles back and forth, it either appears or when un-selected, the value gets removed. Thanks

function functionOne() {
  var x = document.getElementById("wheels").value;
  document.getElementById("demo").innerHTML = x;

}
<input type="checkbox" id="wheels" onchange="functionOne()" value="feature 1">

<div id="demo"></div>


Solution

  • Check the state of the checkbox before you read the value.

    function functionOne(cb) {
      var x = cb.checked ? cb.value : '';
      document.getElementById("demo").innerHTML = x;
    
    }
    <input type="checkbox" id="wheels" onchange="functionOne(this)" value="feature 1">
    
    <div id="demo"></div>