javascript - 在单选按钮选择上显示元素
问题描述
我想在 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 中。
解决方案
您需要为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>
推荐阅读
- security - HTTPS 标头或帖子正文更安全吗?
- google-sheets - 根据单元格值在工作表之间移动行
- python - 为什么默认的 pylintrc 有这么多禁用的消息?
- .net-core - 在 .netcore API 项目中实现 Microsoft Graph API
- javascript - 预定数量的捕获组
- twitter - 如何将 Neo4j 沙盒项目数据(俄罗斯 Twitter 巨魔)直接带到我本地笔记本电脑上的 Neo4j 桌面
- vue.js - 如何过滤一些 vuex 数据以响应选择更改
- r - 边缘上的 R partykit::ctree 偏移标签
- java - 如何修复 ApplicationResources_fr.properties 损坏
- excel - 提示用户根据单元格值保存 Excel 文件名(使用 VBA)