/* html*/ <div class="form__row"> <label class="form__label">Cadence</label> <input class="form__input form__input--cadence" placeholder="step/min" /> </div> <div class="form__row form__row--hidden"> <label class="form__label">Elev Gain</label> <input class="form__input form__input--elevation" placeholder="meters" /> </div> /* Map JS*/ inputType.addEventListener("change", (e) => updateSelect(e)); function updateSelect(e) { const { target } = e; const value = target.value; const cadenceRow = inputCadence.closest(".form__row"); const elevationRow = inputElevation.closest(".form__row"); // Remove the hidden class from both rows first cadenceRow.classList.remove("form__row--hidden"); elevationRow.classList.remove("form__row--hidden"); const selected = { cycling: elevationRow, running: cadenceRow, }; selected[value].classList.add("form__row--hidden"); } /* with a reusable function */ const inputType = document.querySelector('.form__input--type'); inputType.addEventListener("change", function (e) { const value = e.target.value; // run the toggleFieldVisibility here toggleFieldVisibility(value, { running: '.form__input--elevation', cycling: '.form__input--cadence', }); }); function toggleFieldVisibility(selectedType, hiddenFieldMap) { // First remove hidden class from all mapped fields Object.values(hiddenFieldMap).forEach(selector => { const row = document.querySelector(selector)?.closest('.form__row'); row?.classList.remove('form__row--hidden'); }); // Then hide the one mapped to the selected type const selectorToHide = hiddenFieldMap[selectedType]; const rowToHide = document.querySelector(selectorToHide)?.closest('.form__row'); rowToHide?.classList.add('form__row--hidden'); }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter