Keaire Keaire - 3 years ago 129
Javascript Question

Show next select element if the previous one have an option selected

I'm not very practical with jQuery/Javascript, I know how to do it if I specific manually every ID but I know that it's not a good approach to use.

I'm searching for a way, fully dynamic in jQuery, that if a select element (initially with an empty value) have an option selected (value not empty), it show the next select with the same class.

Ex.

That's the HTML:

<div id="sel1" class="sel" style="display: block;">
<select id="select1">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>

<div id="sel2" class="sel">
<select id="select2">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>

<div id="sel3" class="sel">
<select id="select3">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>


And that's the CSS:

.sel {
display: none;
}



  1. So, basically the page start with the first sel1 displayed.

  2. If I select an option that have a value not empty (ex. Option1) it show me automatically the next div with class sel (id=sel2).

  3. If I select an option not empty in the sel2, it show me automatically the next div with class sel (id=sel3)

  4. If I select an option not empty in the sel3 it stop because there's no next div with class sel.


Answer Source

Maybe like so:

$('select[id^=select]').on('change', function(){
    if($(this).val().length > 0) {
        $(this).closest('div.sel').next('div.sel').css('display', 'block');
    }
});
.sel {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sel1" class="sel" style="display: block;">
    <select id="select1">
        <option selected value>Default Option</option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
    </select>
</div>

<div id="sel2" class="sel">
    <select id="select2">
        <option selected value>Default Option</option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
    </select>
</div>

<div id="sel3" class="sel">
    <select id="select3">
        <option selected value>Default Option</option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
    </select>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download