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?
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.
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 .
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 .
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With