refresh show/hide div using jquery dropdown

2019-06-05 23:08发布

问题:

in my code i show/print div using jquery & dropdown . this worked but when refresh my page dropdown not reset and show old select. e.x jquery Code :

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

HTMl OUTPUT :

<form>
 <select id="dropdown" name="dropdown">
  <option value="0">Choose</option>
  <option value="area1">DIV Area 1</option>
  <option value="area2">DIV Area 2</option>
  <option value="area3">DIV Area 3</option>
 </select>
</form>
<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>

Online Demo: HERE

Problem : after click and choose any div this show result div But after refresh not reset dropdown and hide div result. For better understand after choose dropdown rightClick in jsffiddle result and refresh this frame (result) U see my problems.

Print SCR of Problem :

Thanks

回答1:

you should use Htmlhiddeninput which contain your selected value of the dropdown than render the div

  $(document).ready(function(){

   $('.box').hide();
  // First Way :

   $('#HiddenInput').empty();
   $('#HiddenInput').val($('#dropdown').val());
   var value =  $('#HiddenInput').val();
   $('#dropdown').val(value);
   $('#div' + value).show();


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

Here See DEMO : http://jsfiddle.net/pXdS6/16/



回答2:

I have the same problem in Firefox.

And it seems reasonable. If you reload the page, and have "save form data" on - it repopulates the form automaticly for you. And since you only show the selected div on "change" it dosent take into account it might already be changed from default value.

You can then add this

$(document).ready(function(){
 $('.box').hide();

  var selected = $('#dropdown').val();
    if(selected != 0) {
      $('.box').hide();
      $('#div' + selected).show();
    }

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

See: http://jsfiddle.net/pXdS6/

It basicly takes the "select" value on load, and show the div, if not default :)