开发者

Jquery Show Fields depending on Select Menu value but on page load

This question refers to the question Show/hide fields depending on select value

<select id="viewSelector">
   <option value="0">-- Select a View --</option>       
   <option value="view1">view1</option>
   <option value="view2">view2</option>
   <option value="view3">view3</option>
</select>

<div id="view1">
  <!-- content --> 
</div>
<div id="view2a">
  <!-- content --> 
</div>
<div id="view2b">
  <!-- content --> 
</div>
<div id="view3">
  <!-- content --> 
</div>



$(document).ready(function() {
  $.viewMap = {
    '0' : $([]),
    'view1' : $('#view1'),
    'view2' : $('#view2a, #view2b'),
    'view3开发者_如何学编程' : $('#view3')
  };

  $('#viewSelector').change(function() {
    // hide all
    $.each($.viewMap, function() { this.hide(); });
    // show current
    $.viewMap[$(this).val()].show();
  });
});

When I select the 2nd item in the menu it shows the corresponding field.

The exception to this is when the on page load the select menu already has the 2nd menu item selected, the field does not show.

As you may be able to tell, I am new to jquery and could definetly use some help with adjusting this code so that the selected item's field is shown on page load.

Thanks,

Tim


The easiest thing to do in this case is just trigger the change handler you already have/need, like this:

$('#viewSelector').change(function() {
  $.each($.viewMap, function() { this.hide(); });
  $.viewMap[$(this).val()].show();
}).change(); //only change to your code!

This just triggers the change event on the same selector right after you bound it, so it occurs on document.ready (where you're binding) as well as when it changes. .change() with no arguments is equivalent to .trigger('change').


Move the code into a function and call it onload as well -

 $(document).ready(function() {

  function toggleDivs(val) {
        $.each($.viewMap, function() { this.hide(); });
        $.viewMap[val].show();
  }

  toggleDivs($('#viewSelector').val());

  $.viewMap = {
        '0' : $([]),
    'view1' : $('#view1'),
    'view2' : $('#view2a, #view2b'),
    'view3' : $('#view3')
  };

  $('#viewSelector').change(function() {
    toggleDivs($(this).val());
  });
});

Of course, you probably wouldn't need $.viewMap if you just stored the selector data in the HTML of the <option>.. data-selectors="#view2a, #view2b"

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜