Ad

How To Apply Different Section To A Radio Button

- 1 answer

I have this project for school, to show different drop-down option for each selected radio button. I tried few JavaScript code but it wasn't working at all.

I need when clicked on Sizes radio button to show the correspondent sizes drop-down selectors. As well for the colors. To show only colors drop-down selectors

Thank you in advance for the help.

Bellow is the code

<form>
  <fieldset>
    <p>

     <input type = "radio"
            name = "sizes"
            id = "sizes"
            value = ""
            checked = "checked">
     <label for = "sizes"> Sizes </label>

     <input type = "radio"
            name = "colors"
            id = "colors"
            value = "">
     <label for = "colors"> Colors </label>

    </p>       
  </fieldset>     
</form>



<label for="small-size"> Small Size </label>
  <select name="size" id="size">
     <option value="1" selected> Size 1 </option>
     <option value="2"> Size 2 </option>
     <option value="3"> Size 3 </option>
   </select>

<label for="big-size"> Big Size </label>
  <select name="size" id="size">
     <option value="1" selected> Size 1 </option>
     <option value="2"> Size 2 </option>
     <option value="3"> Size 3 </option>
   </select>

<label for="dark"> Dark Colors </label>
   <select name="canvas" id="canvas">
      <option value="1" selected> Color 1</option>
      <option value="2"> Color 2 </option>
      <option value="3"> Color 3 </option>
   </select>

<label for="light"> Light Colors </label>
   <select name="canvas" id="canvas">
      <option value="1" selected> Color 1</option>
      <option value="2"> Color 2 </option>
      <option value="3"> Color 3 </option>
   </select>



https://jsfiddle.net/Farsoun/dw813ky2/9/

Ad

Answer

You should really show at least an attempt of some sort when posting something like this, especially with the JavaScript tag.

Anyways, to do this you would want to listen to when a user clicks on a radio button and show/hide the corresponding elements.

Here's a sample:

document.getElementById('colors').addEventListener("click", function(e){
   document.getElementById("colors-selections").style.display = "block";
   document.getElementById("size-selections").style.display = "none";
});

If you have more than two elements in the future, I'd recommend using an onchange so you can hide it once it's untoggled rather than hiding everything else everytime a new radio button is clicked.

If you want to use just CSS you're going to have to used the :checked attribute and hide or display another element also:

Other users already have asked about this, ex: https://stackoverflow.com/a/50921066/4107932

Ad
source: stackoverflow.com
Ad