Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I show a hidden div when a select option is selected?

I want to use plain JavaScript. I have a drop down list (<select> with a number of <option>s). When a certain option is selected I want a hidden div to display.

<select id="test" name="form_select">    <option value="0">No</option>    <option value ="1" onClick"showDiv()">Yes</option> </select> <div id="hidden_div" style="display: none;">Hello hidden content</div> 

Then I'm trying it with this vanilla JavaScript code:

function showDiv(){    document.getElementById('hidden_div').style.display = "block"; } 

I'm guessing my problem is with the onClick trigger in my options but I'm unsure on what else to use?

like image 707
twigg Avatar asked Apr 15 '13 13:04

twigg


People also ask

How do you show and hide div elements based on dropdown selection?

If you want to hide/show div on dropdown selected, use the jQuery hide() and show(). Before you perform hide or show div on dropdown selection, you need to hide them first using CSS display:none. The display of the div dynamically happen based on the click of the selected dropdown option.

How do I show a div on a select option?

To show a div element when a select option is selected: Add a change event listener to the select element. Each time the event is triggered, check if the specific value was selected. If it was, set the div's display property to block .

How do I hide a div and then show on click?

To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .


2 Answers

Try handling the change event of the select and using this.value to determine whether it's 'Yes' or not.

jsFiddle

JS

document.getElementById('test').addEventListener('change', function () {     var style = this.value == 1 ? 'block' : 'none';     document.getElementById('hidden_div').style.display = style; }); 

HTML

<select id="test" name="form_select">    <option value="0">No</option>    <option value ="1">Yes</option> </select>  <div id="hidden_div" style="display: none;">Hello hidden content</div> 
like image 20
Daniel Imms Avatar answered Sep 24 '22 00:09

Daniel Imms


try this:

function showDiv(divId, element)  {      document.getElementById(divId).style.display = element.value == 1 ? 'block' : 'none';  }
#hidden_div {      display: none;  }
<select id="test" name="form_select" onchange="showDiv('hidden_div', this)">     <option value="0">No</option>     <option value="1">Yes</option>  </select>  <div id="hidden_div">This is a hidden div</div>
like image 68
Mihai Matei Avatar answered Sep 20 '22 00:09

Mihai Matei