tags:

views:

20

answers:

3

Hello All

I have the following JQuery, I want to display the default divarea1 visible when the user goes to the page, I am newbie to Jquery so any help would be great.

Best SPS

 <script type="text/javascript">
     $(document).ready(function() {
         $('.box').hide();
         $('#dropdown').change(function() {
             $('.box').hide();
             $('#div' + $(this).val()).show();
         });
     }); 
</script> 


 <select id="dropdown" class="boxformwh" name="dropdown"> 
    <option style="margin:20px;" value="area1"><b>DIV Area 1</b></option> 
    <option style="margin:20px;" value="area2"><b>DIV Area 2</b></option> 
    <option style="margin:20px;" value="area3"><b>DIV Area 3</b></option> 
 </select> 


  <div>
    <div id="divarea1" class="box">DIV Area 1</div> 
    <div id="divarea2" class="box">DIV Area 2</div> 
    <div id="divarea3" class="box">DIV Area 3</div> 
  </div>
A: 

You just need to trigger the change handler on page load as well, like this:

$(document).ready(function() {
  $('.box').hide();
  $('#dropdown').change(function() {
    $('.box').hide();
    $('#div' + $(this).val()).show();
  }).change();
}); 

You can give it a try here, calling .change() without any arguments is a shortcut to .trigger('change') which will run the handler you just bound...so it'll use the initial value of the dropdown on page load.

Nick Craver
NickThanks for you help!
SPS101
A: 

You are explicitly hiding all .box elements, so you need to show divarea1 element explicitly as well. The onchange will bork as expected.

<script type="text/javascript">
     $(document).ready(function() {
         $('.box').hide();
         $('.box:first').show();
         $('#dropdown').change(function() {
             $('.box').hide();
             $('#div' + $(this).val()).show();
         });
     }); 
</script> 

Changed to show the first .box div, that was not tied to a specific div and will show first.

Dustin Laine
A: 
<script type="text/javascript">
     $(document).ready(function() {
         $('.box').hide();
         $('#divarea1').show();
         $('#dropdown').change(function() {
             $('.box').hide();
             $('#div' + $(this).val()).show();
         });
     }); 
</script> 
Jasper