Home > Software engineering >  Dropdown selections jQuery
Dropdown selections jQuery

Time:09-26

I am making a dropdown and want to show the div class="residential-options" when the id="residential" is selected and show the div class="commercial-options" when the id="commercial" is selected.

heres my HTML:

<div class= "row">
                <select id='building-type'>  
                    <option disabled selected value> -- select an option -- </option>
                    <option id="residential" value="residential" [...]>Residential</option>
                    <option id="commercial" value="commercial " [...]>Commercial</option>
                    <option id="corporate" value="corporate" [...]>Corporate</option>
                    <option id="hybrid" value="hybrid" [...]>Hybrid</option>

                </select>    
            </div>

        

            <div class="residential-options">

                <div id="number-of-apartments" >
                        <label>N. of Apartments *</label>
                        <input [...]>
                </div>                
             
                
                <div id="number-of-basements" >
                    <label>N. of Basements *</label>
                    <input [...]>
                </div>
            
            </div> 

            <div class="commercial-options">

                <div id="number-of-floors" >
                        <label>N. of Floors *</label>
                        <input [...]>
                </div>

heres my jQuery:

$("#building-type").change(function() {
    ($('#residential').is(':checked'))
    $('.residential-options').show();
    $('.commercial-options').hide();
    $('.corporate-options').hide();
    $('.hybrid-options').hide()
    });
$("#building-type").trigger("change");

$("#building-type").change(function() {
    ($('#commercial').is(':checked'))
    $('.commercial-options').show();
    $('.residential-options').hide();
    $('.corporate-options').hide();
    $('.hybrid-options').hide()
    });
$("#building-type").trigger("change");

it only shows the div class="commercial-options" whatever I click on. Thanks for your help!

CodePudding user response:

you can change your code to something like this:- get the selected value from the building type . compare the value using if, else if statements and inside if / else if statements show and hide your div's using class attribute.

CodePudding user response:

Your code can be simplified greatly, including removing the .trigger() calls.

$("#building-type").change(function() {
    $('div[class*="options"]').hide(); // hide all '*-option' divs
    // Determine which option was selected and display the corresponding div:
    ['residential', 'commercial', 'corporate', 'hybrid'].forEach(function(base){
        if ($('#'   base   ':checked').length) {
            $(`.${base}-options`).show();
        }
    })
})
  • Related