I would like to show input text
field on radio button
selection in vanilla JavaScript.
What am I missing?
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>
I’m aware that there are similar questions previously asked on Stack Overflow, but all of them are in jQuery.
You need to add an event listener for the
click
event of each of the radio buttons.Check this on Fiddle
Hope this will be helpful.
You can use event delegation on the
fieldset
- whenever it observes a bubbledchange
event, you know that one of the<input>
s has been selected, so you can then set thestyle
of thetotal
input field. Use{ once: true }
so that the listener only gets triggered once: