I need to show/hide three forms depending on dropdown selected option without using conditional statements. Is it possible?
>Solution :
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!