Estoy haciendo un menú desplegable y quiero mostrar div class="residential-options" cuando se selecciona id="residencial" y mostrar div class="commercial-options" cuando se selecciona id="commercial".
aquí está mi 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>aquí está mi 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");solo muestra div class="commercial-options" en lo que sea que haga clic. ¡Gracias por tu ayuda!
Su código se puede simplificar enormemente, incluida la eliminación de las llamadas .trigger() .
$("#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(); } }) })puede cambiar su código a algo como esto: obtenga el valor seleccionado del tipo de edificio. compare el valor usando las declaraciones if, else if y dentro de las declaraciones if / else if muestran y ocultan el atributo de clase de uso de su div.