Home > front end >  Show/hide multiple forms depending on dropdown without conditional statements
Show/hide multiple forms depending on dropdown without conditional statements

Time:01-03

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

CodePudding user response:

You can do it like so, please reference with: https://api.jquery.com/on/

The idea is to apply event listener for each select option.

const $selectElement = $('#forms');

$selectElement.on('click', 'option', (event) => {
  $('form').css('display', 'none');
  $(`[data-id="${event.target.value}"]`).css('display', 'block');
});
form {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="forms">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<form data-id="1">
  <span>1</span>
</form>

<form data-id="2">
  <span>2</span>
</form>

<form data-id="3">
  <span>3</span>
</form>

CodePudding user response:

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!

  • Related