I've tried looking around and there are similar problems, but mine is way more simple, but yet, I can't find a solution within these forums.
While learning jQuery, I'm trying to show a DIV when an item/option from a select drop down is selected, and hide that same DIV when any other option in the select drop down is selected.
select HTML:
<select name="source" id="source">
<option value="null" selected="selected">—Select—</option>
<option value="s1">Source 1</option>
<option value="s2">Source 2</option>
<option value="sother">Other</option>
</select>
DIV I need to show when 'Other' is selected:
<div id="specify-source">Other source here...</div>
When any other option in the select menu is selected, the above DIV shouldn't be visible.
I've tried this jQuery but of course it doesn't work properly:
$(function() {
$.viewMap = {
'sother' : $('#specify-source')
};
$('#source').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
});
});
Any help you can give me, I'd greatly appreciate it.
Thanks,
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.
To show a hidden div when a select option is selected, you can set the value “style. display” to block.
Store the values of the selected elements in variable using . attr() method. Now check for the element whether any element is selected or not. If yes, use show() method for displaying the element for the selected element, otherwise use hide() method for hiding.
The hidden attribute hides the <select> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <select> element is not visible, but it maintains its position on the page.
I see what you're trying to do with the view map. Simplify it with:
$('#source').change(function() {
($(this).val() == "sother") ? $('#specify-source').show() : $('#specify-source').hide();
});
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