Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: show an element from select drop down, hide it when other option selected

Tags:

jquery

select

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">&mdash;Select&mdash;</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,

like image 753
Ricardo Zea Avatar asked Apr 16 '10 20:04

Ricardo Zea


People also ask

How can I show and hide elements based on selected option with jQuery?

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.

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

To show a hidden div when a select option is selected, you can set the value “style. display” to block.

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

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.

How do you hide a selected element?

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.


1 Answers

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();
});
like image 100
Amit Avatar answered Nov 14 '22 09:11

Amit