简体   繁体   中英

Can't change innerHTML when using Radio Buttons

I'm trying to change the but at the moment it currently isn't changing text when I check other radio buttons.

I've tried changing the values in my HTML inputs, and searched through the mozilla JS helpers but can't seem to find a fix.

 let shapeChoice = document.querySelector('input[name="shape"]:checked').value; switch (shapeChoice) { case 'circV': document.getElementById("debug1").innerHTML = "Circle Area" break; case 'rectV': document.getElementById("debug1").innerHTML = "Rectangle Area" break; case 'triV': document.getElementById("debug1").innerHTML = "Triangle Area" break; case 'paraV': document.getElementById("debug1").innerHTML = "Parallelogram Area" break; default: doucment.getElementById("debug1").innerHTML = "Default" }
 <div id="radioHeader"> <input type="radio" name="shape" value="circV" onclick="" checked> <label for="circleID">Circle</label> <input type="radio" name="shape" value="rectV"> <label for="rectangleID">Rectangle</label> <input type="radio" name="shape" value="triV"> <label for="triangleID">Triangle</label> <input type="radio" name="shape" value="paraV"> <label for="parallelogramID">Parallelogram</label> <br> <p id="debug1"></p> </div>

on load "Circle Area" should be displayed underneath the radio boxes, but upon checking the other radios, it change to the corresponding shape's + Area.

However, I'm only getting "Circle Area" even if I check another radio box.

You should attach an onclick event. when event occur then check all cases. as i bellow described.

 function radioClicked(){ let shapeChoice = document.querySelector('input[name="shape"]:checked').value; switch (shapeChoice) { case 'circV': document.getElementById("debug1").innerHTML = "Circle Area" break; case 'rectV': document.getElementById("debug1").innerHTML = "Rectangle Area" break; case 'triV': document.getElementById("debug1").innerHTML = "Triangle Area" break; case 'paraV': document.getElementById("debug1").innerHTML = "Parallelogram Area" break; default: doucment.getElementById("debug1").innerHTML = "Default" } }; radioClicked();
 <div id="radioHeader" onload="radioClicked()" onclick="radioClicked()" > <input type="radio" name="shape" value="circV" onclick="" checked> <label for="circleID">Circle</label> <input type="radio" name="shape" value="rectV"> <label for="rectangleID">Rectangle</label> <input type="radio" name="shape" value="triV"> <label for="triangleID">Triangle</label> <input type="radio" name="shape" value="paraV"> <label for="parallelogramID">Parallelogram</label> <br> <p id="debug1"></p> </div>

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