Skip to content Skip to sidebar Skip to footer

Show Element On Radio Button Selection

I would like to show input text field on radio button selection in vanilla JavaScript. What am I missing? I’m aware that there are similar questions previously asked on Stack Ov

Solution 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><inputtype="radio"name="size"value="6"id="six"required>6-inch</label><label><inputtype="radio"name="size"value="8"id="eight">8-inch</label><label><inputtype="radio"name="size"value="12"id="twelve">12-inch</label></fieldset><inputtype="text"name="total"readonly></form>

Check this on Fiddle Hope this will be helpful.

Solution 2:

You can use event delegation on the fieldset - whenever it observes a bubbled change event, you know that one of the <input>s has been selected, so you can then set the style of the total input field. Use { once: true } so that the listener only gets triggered once:

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><inputtype="radio"name="size"id="six">6-inch</label><label><inputtype="radio"name="size"id="eight">8-inch</label><label><inputtype="radio"name="size"id="twelve">12-inch</label></fieldset><inputtype="text"name="total"readonly></form>

Solution 3:

You need to add an event listener for the click event of each of the radio buttons.

<form><fieldset><legend>Choose Size</legend><label><inputtype="radio"name="size"id="six"required>6-inch</label><label><inputtype="radio"name="size"id="eight">8-inch</label><label><inputtype="radio"name="size"id="twelve">12-inch</label></fieldset><inputtype="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>

Post a Comment for "Show Element On Radio Button Selection"