Skip to content
Advertisement

Show hidden drop down based on selected option in another drop down with jQuery

I’m trying to figure out how to show hidden div but I’m a little rusty on jQuery.

So when a user selects “Yes” from Menu1 dropdown, I want the Menu2 dropdown to show up. l’m using style="visibility: hidden; to hide Menu2.

enter image description here enter image description here

    <div class="form-row">
        <div class="form-group col-md-4">
            <label for="inputEmail4">Menu1</label>
            <select class="form-control" name="name" id="Menu1">
                <option value="">--Please choose an option--</option>
                <option value="Yes">Yes</option>
                <option value="No">No</option>
            </select>
        </div>
        **<div class="form-group col-md-4" style="visibility: hidden;">**
            <label for="inputPassword4">Menu2</label>
            <select class="form-control" name="pets" id="Menu2">
                <option value="">--Please choose an option--</option>
                <option value="dog">Dog</option>
                <option value="cat">Cat</option>
            </select>
        </div>

Advertisement

Answer

You can use this siple javascript code for that. No need to go for jQuery here. just give a id to hidden div so we can access it.

        document.getElementById('Menu1').onchange = e => {
            let hiddenElement = document.getElementById('hiddenDiv')
            e.target.value == 'Yes' ?
                hiddenElement.style.visibility = 'visible' :
                hiddenElement.style.visibility = 'hidden'
        }
    <div class="form-group col-md-4">
        <label for="inputEmail4">Menu1</label>
        <select class="form-control" name="name" id="Menu1">
            <option value="">--Please choose an option--</option>
            <option value="Yes">Yes</option>
            <option value="No">No</option>
        </select>
    </div>
    **<div class="form-group col-md-4" id='hiddenDiv' style="visibility: hidden;">**
        <label for="inputPassword4">Menu2</label>
        <select class="form-control" name="pets" id="Menu2">
            <option value="">--Please choose an option--</option>
            <option value="dog">Dog</option>
            <option value="cat">Cat</option>
        </select>
    </div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement