Search code examples
javascripthtmlcssformsshow-hide

How do you show and hide field in a form depending on drop-down selections?


I am trying to create a form in which would show and hide a specific field of a form when certain elements of a drop-down list is selected.

I currently have found a way to hide it using CSS but I am not sure on how you would use CSS or JavaScript to unhide them when specific values in the drop down list are selected.

This is what I have got at the moment: HTML:

    <td><label for="ageRange">Age: </label><font color="red">*</font></td>
    <td><select name="ageRange" id="ageRange">
            <option value="0">Select</option>
            <option value="0-16">0-16</option>
            <option value="17-25">17-25</option>
            <option value="26-40">26-40</option>
            <option value="41-60">41-60</option>
            <option value="60+">61+</option>
        </select>
    </td>
</tr>
<tr>
    <td><label for="license" class="hidden">Driver's License: </label></td>
    <td><input type="test" name="license" id="license" class="hidden"><br></td>

CSS:

    input.hidden {
        display: none
    }
    label.hidden {
        display: none
    }

What I want to happen is for the field "Driver's License" to stay hidden unless in the drop-down list (ageRange) you select any values except for "Select" and "0-16."


Solution

  • Here is how you can do so . Just check the selected value by dropdown and compare with value. If selectedValue found 0-16 just add hidden class on tr remove otherwise.

    document.getElementById("toHide").classList.add("hidden");
    
    function myFunction(){
    var selectedVal = document.getElementById("ageRange").value;
     if(selectedVal == "0-16" || selectedVal=="0" ){
       document.getElementById("toHide").classList.add("hidden");
        document.getElementById("license").value='';
      } else{
      document.getElementById("toHide").classList.remove("hidden");
        document.getElementById("license").value=selectedVal;
     }
    }
    .hidden {
            display: none
        }
    <table border="2">
     <td><label for="ageRange">Age: </label><font color="red">*</font></td>
        <td><select name="ageRange" id="ageRange"  onchange="myFunction()">
                <option value="0">Select</option>
                <option value="0-16">0-16</option>
                <option value="17-25">17-25</option>
                <option value="26-40">26-40</option>
                <option value="41-60">41-60</option>
                <option value="60+">61+</option>
            </select>
        </td>
    </tr>
    <tr id="toHide">
        <td ><label for="license" >Driver's License: </label></td>
        <td ><input type="test"  name="license" value=""  id="license" ><br></td>
        </tr>
        </table>