dames dames - 4 months ago 33
HTML Question

creating a dependent html dropdown list using pure JavaScript

I am trying to create a dependent drop down list where if option one is selected it only shows

div class option1
and if option 2 is selcted it shows
div class option2
, Im not that good at JavaScript, (not jQuery) Im seeking some assistance please

<select id="lstFruits" >
<option value="1">Mango</option>
<option value="2">Apple</option>
</select>

<div class ="option1">
<br/><br/>
Colour1 <input type="text"/>
<br/>
Taste1 <input type="text"/>
<br/>
weight1 <input type="text"/>
</div>

<div class="option2">
<br/><br/>
Colour2 <input type="text"/>
<br/>
Taste2 <input type="text"/>
<br/>
weight2 <input type="text"/>
</div>

Answer

You could use this code:

// Let the DOM load before addressing elements:
document.addEventListener('DOMContentLoaded', function () {
    var fruits = document.querySelector('#lstFruits'),
        divs = [document.querySelector('.option1'),
                document.querySelector('.option2')];

    function showMatchingOptions() {
        // Show and hide the correct div, based on the selected value
        divs[+this.value-1].style.display = '';
        divs[2-this.value].style.display = 'none';
    }
                
    // Execute the above function on every change in the select list
    fruits.addEventListener('change', showMatchingOptions);
    
    // Execute the above function also on page load, so we 
    // start with a consistent situation.
    showMatchingOptions.call(fruits);
});
<select id="lstFruits" >
    <option value="1">Mango</option>
    <option value="2">Apple</option>
</select>

<div class ="option1">
    <br/><br/>
    Colour1 <input type="text"/>
    <br/>
    Taste1 <input type="text"/>
    <br/>
    weight1 <input type="text"/>
</div>

<div class="option2">
    <br/><br/>
    Colour2 <input type="text"/>
    <br/>
    Taste2 <input type="text"/>
    <br/>
    weight2 <input type="text"/>
</div>

More than 2 elements:

If you have more than 2 elements, you would use a for loop:

var fruits = document.querySelector('#lstFruits'),
    divs = [document.querySelector('.option1'),
            document.querySelector('.option2'),
            document.querySelector('.option3')];

function showMatchingOptions() {
    // Show and hide the correct div, based on the selected value
    for (var i = 0; i < 3; i++) {
        divs[i].style.display = +this.value-1 === i ? '' : 'none';
    }
}
Comments