Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show & hide content based on select value

Tags:

jquery

I have a this Html code

<select class="selectOption">
    <option>Analytics</option>
    <option>Translation</option>
    <option>Poll</option>
</select>

<div id="changingArea">
    <div id="Analytics" class="desc">Analytics</div>
    <div id="Translation" class="desc">Translation</div>
    <div id="Poll" class="desc">Poll</div>
</div>​

Css

.desc {display: none;}​

Js

$(function(){
      $('.selectOtion').change(function(){
        var selected = $(this).find(':selected').text();
        $(".desc").hide();
         $('#' + selected).show();
      });
});

The problem now it that all the div elements are hidden in page load. I want to show the first option value by default and when changed the div content is also change.

Example http://jsfiddle.net/bsqVm/

EDIT:

Thank you guys for your help

First there was a typo in my code, so 'selectOtion' should be 'selectOption'

Second to make the default select to show we can trigger the change event on DOMReady as 'undefined' solution

so the javascript is

$(function(){
      $('.selectOption').change(function(){
        var selected = $(this).find(':selected').text();
        //alert(selected);
        $(".desc").hide();
         $('#' + selected).show();
      }).change()
 });

or

 $(function(){
  $('#Analytics').show(); // Will show the div
  $('.selectOption').change(function(){
    var selected = $(this).find(':selected').text();
    //alert(selected);
    $(".desc").hide();
    $('#' + selected).show();
  });
 });
like image 850
Ahmad Ajmi Avatar asked Mar 18 '26 13:03

Ahmad Ajmi


2 Answers

There is a typo in your code selectOtion should be selectOption. For showing the the div according to selected value you can trigger the change event on DOMReady.

$(function(){
     $('.selectOption').change(function(){
         var selected = $(this).find(':selected').text();
         $(".desc").hide();
         $('#' + selected).show();
     }).change()
});

http://jsfiddle.net/XCUDF/

like image 104
undefined Avatar answered Mar 21 '26 04:03

undefined


there is a typo in your code

$(function(){
      $('.selectOption').change(function(){
        var selected = $(this).find(':selected').text();
        $(".desc").hide();
         $('#' + selected).show();
      });
});

change $('.selectOtion') to $('.selectOption')

i have updated your fiddle working fine now have a look

http://jsfiddle.net/bsqVm/4/

like image 34
rahul Avatar answered Mar 21 '26 04:03

rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!