开发者

Jquery Dropdown Display Default Div

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开发者_StackOverflow社区').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>


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜