首页 > 解决方案 > 在单选按钮选择上显示元素

问题描述

我想在 vanilla JavaScript 中显示选择input text字段。radio button

我错过了什么?

const form = document.querySelector("form");
const size = form.elements["size"];
const total = form.elements["total"];

total.style.display = "none";

for (var i = 0; i < size.length; i++) {
  if (size[i].checked) {
    total.style.setProperty("display", "inherit");
  } else {
    total.style.setProperty("display", "none");
  }
}
<form>
<fieldset>
  <legend>Choose Size</legend>
  <label><input type="radio" name="size" id="six">6-inch</label>
  <label><input type="radio" name="size" id="eight">8-inch</label>
  <label><input type="radio" name="size" id="twelve">12-inch</label>
</fieldset>

<input type="text" name="total" readonly>
</form>

我知道以前在 Stack Overflow 上问过类似的问题,但它们都在 jQuery 中。

标签: javascripthtmlforms

解决方案


您需要为click每个单选按钮的事件添加一个事件侦听器。

<form>
<fieldset>
  <legend>Choose Size</legend>
  <label><input type="radio" name="size" id="six" required>6-inch</label>
  <label><input type="radio" name="size" id="eight">8-inch</label>
  <label><input type="radio" name="size" id="twelve">12-inch</label>
</fieldset>

<input type="text" name="total" readonly>
</form>
<script>
const form = document.querySelector("form");
const total = form.elements["total"];
const radios = form.querySelectorAll("input[name=size]");
total.style.display = "none";
radios.forEach(i=>{
i.addEventListener('click', function(e){
if(this.checked){
  total.style.setProperty("display", "inherit");
  total.value = this.id;//sets value of readonly input to the id of the selected radio button
} 
});
});
</script>


推荐阅读