Populate select element with javascript

Written by Kuligaposten

Populate select element with javascript

Basically, the 2nd select is initially hidden, only revealed if the user select’s ‘Yes’ in the first select.

Then, depending on which option the user select in the 2nd (now revealed) select, will open up a specific DIV containing additional components. Example, if Audio is selected, then the Audio DIV is displayed. If Video is selected, only the Video DIV is displayed.

If the user goes back to the first Select and chooses ‘No’, the DIV and the 2nd Select go back to hidden.

Would a Collapse work here for the DIV area? I could delete the default button, but then how to get it to open up the respective DIV depending on what was selected in Select 2?

Thank you.

You can try with this

const selectBrand = document.getElementById('brand');
const selectYear = document.getElementById('year');

selectBrand.addEventListener('change', () => {
  selectYear.innerHTML = '';
  selectYear.removeAttribute('disabled');
  const placeholderOption = document.createElement('option');
  placeholderOption.text = '-Select A Year-';
  placeholderOption.value = '';
  selectYear.append(placeholderOption);
  fetch('assets/js/auto_data.json')
    .then((response) => response.json())
    .then((autos) => {
      const years = autos[selectBrand.value];
      if (years) {
        years.forEach((year) => {
          const option = document.createElement('option');
          option.value = year;
          option.text = year;
          selectYear.append(option);
        });
      } else {
        selectYear.setAttribute('disabled', '');
      }
    })
    .catch((error) => console.error('Error fetching autos:', error));
});
document.getElementById('carsForm').addEventListener('reset', () => {
  selectYear.innerHTML = '';
  selectYear.setAttribute('disabled', '');
});

here is an example with a simple submitFormHandler

Brand
Color
Year
Options
Steering wheel

There are 3 ids adapt them to fit your needs.

  • The select element for the car brand, change the Id in the script to what you have
  • The select element for the years, change the Id in the script to what you have
  • The form element, change the Id in the script to what you have

Good luck with your forms

Go back