我想在香草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中。
答案 0 :(得分:1)
您需要为每个单选按钮的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>
答案 1 :(得分:1)
您可以在fieldset
上使用事件委托-每当它观察到冒泡的change
事件时,您就知道已选择<input>
个事件之一,因此可以设置style
输入字段中的total
。使用{ once: true }
,以便侦听器仅被触发一次:
const total = document.querySelector('input[name="total"]');
document.querySelector('fieldset').addEventListener('change', () => {
total.style.display = "inherit";
}, { once: true });
input[name="total"] {
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>
答案 2 :(得分:1)
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++) {
size[i].onclick = function() {
if (this.checked) {
total.style.setProperty("display", "inherit");
total.value = this.value;
} else {
total.style.setProperty("display", "none");
}
}
}
<form>
<fieldset>
<legend>Choose Size</legend>
<label><input type="radio" name="size" value="6" id="six" required>6-inch</label>
<label><input type="radio" name="size" value="8" id="eight">8-inch</label>
<label><input type="radio" name="size" value="12" id="twelve">12-inch</label>
</fieldset>
<input type="text" name="total" readonly>
</form>
在Fiddle上进行检查
希望这会有所帮助。