简体   繁体   中英

Display different divs using input checkbox

I want to use 3 input checkbox to display 3 different div. I am using this code but the only one working is "Course 1" and I can't figure out why. I guess it is something pretty easy, but I can't see it:

 document.getElementById('checkbox1'); checkbox1.onchange = function() { if (checkbox1.checked) { course1.style.display = 'block'; } else { course1.style.display = 'none'; } }; document.getElementById('checkbox2'); checkbox2.onchange = function() { if (checkbox2.checked) { course2.style.display = 'block'; } else { course2.style.display = 'none'; } }; document.getElementById('checkbox3'); checkbox3.onchange = function() { if (checkbox3.checked) { course3.style.display = 'block'; } else { course3.style.display = 'none'; } }; 
 <form> <label class="switch"> <input type="checkbox" id="checkbox1" checked="true"> Course 1 </label> </form> <form> <label class="switch"> <input type="checkbox" id="checkbox2" checked="true"> Course 2 </label> </form> <form> <label class="switch"> <input type="checkbox" id="checkbox3" checked="true"> Course 3 </label> </form> <br> <div id="course1"> Text course 1 </div> <br> <div id="course2"> Text course 2 </div> <br> <div id="course2"> Text course 3 </div> 

Example: https://codepen.io/antonioagar1/pen/dqGaoO

You can try this simple code instead of your own code:

 document.addEventListener("change", function(ev){
    if(ev.target.id.substr(0,8)=="checkbox") document.querySelector("[id='course"+ev.target.getAttribute("id").slice(-1)+"']").style.display=ev.target.checked?"block":"none";
 });
  • you have two div with id course2 . first, change it to course3 and then try.

Check result online

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM