Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show/hide multiple forms depending on dropdown without conditional statements

I need to show/hide three forms depending on dropdown selected option without using conditional statements. Is it possible?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Yes. I would just use a Map and do something like this (UNTESTED!):


const myDropdown = document.querySelector("#myDropdown");

const resetVisibilityOfForms = () => Object.keys(formMap).forEach(form => document.querySelector(form).style.visibility = 'hidden');

const formMap = {
    'default': () => resetVisibilityOfForms(),
    'formId1': () => resetVisibilityOfForms() && document.querySelector('myForm1').style.visibility = 'visible',
    'formId2': () => resetVisibilityOfForms() && document.querySelector('myForm2').style.visibility = 'visible'
};

myDropdown.onchange = (e) => {
  const selectedForm = myDropdown.options[myDropdown.selectedIndex].value;

  formMap[selectedForm]();
};

// just hide all the forms by default...
resetVisibilityOfForms();

This would work with HTML like the following:

<form id="formId1">....</form>
<form id="formId2">....</form>

<select id="myDropdown">
    <option value="default">Choose a form</option>
    <option value="formId1">Form 1</option>
    <option value="formId2">Form 2</option>
</select>

There are many ways to improve the above code too. You could simplify the map, create a different type of map, use an array or any number of other different approaches. Point isn’t to create a production ready example to the above though – just to create an example to give you some ideas of how to go about it.

Good luck!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading