使用单选按钮时无法更改innerHTML

时间:2019-11-10 18:52:21

标签: javascript html

我正在尝试更改,但是目前我在检查其他单选按钮时仍未更改文本。

我尝试更改HTML输入中的值,并搜索了mozilla JS帮助器,但似乎找不到修复程序。

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>

在加载时,“圆形区域”应显示在单选框下方,但是在检查其他单选框后,它将变为相应形状的+区域。

但是,即使我选中另一个单选框,我也只会得到“圆圈区域”。

1 个答案:

答案 0 :(得分:2)

您应该附加一个onclick事件。事件发生时,请检查所有情况。正如我在下面描述的那样。

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>