How to show a hidden div when a select option is selected with JavaScript?

Sometimes, we want to show a hidden div when a select option is selected with JavaScript.

In this article, we’ll look at how to show a hidden div when a select option is selected with JavaScript.

How to show a hidden div when a select option is selected with JavaScript?

To show a hidden div when a select option is selected with JavaScript, we can listen to the change event of the select element to get the option selected.

Then we can set the display CSS property of the element we want to show or hide according to the selected value.

For instance, we write:

<select id="select">
  <option value="0">No</option>
  <option value="1">Yes</option>
</select>

<div id="div" style="display: none;">
  Hello hidden content
</div>

to add a select element and a div to show or hide according to the selected drop down value.

Then we write:

const select = document.getElementById('select')
const div = document.querySelector('div')

select.addEventListener('change', (e) => {
  if (+e.target.value === 1) {
    div.style.display = 'block'
  } else {
    div.style.display = 'none'
  }
})

to show or hide the div when we select a new value in the drop down.

Then we use document.getElementById to select each element.

Next, we call select.addEventListener with 'change' and the change event listener to add a change event listener.

In the event listener, we check if e.target.value is 1 after it’s converted to a number.

If that’s true, we set div.style.display to 'block' to display it.

Otherwise, we set display.style.display to hide it.

Conclusion

To show a hidden div when a select option is selected with JavaScript, we can listen to the change event of the select element to get the option selected.

Then we can set the display CSS property of the element we want to show or hide according to the selected value.