开发者

JavaScript issue in IE when using the back button

I have a form where users can query about two different regions. Form elements for region one are shown by default when the page first loads, while form elements for region two are hidden. I have a select box where users can choose which region they wish to query about, and a bit of JavaScript to show and hide different portions of the form depending on what the region is.

This works fine in Firefox and IE except when the user presses the browser back button in IE, which happens often when users wish to make a slightly different query. If the user queried about region two, then pressed the back button in IE, the region selector still says "Region Two" but form elements for region one are shown. I expect form elements for region two to still show like Firefox does, but how?

The following is a brief example of my code:

<script language="javascript" type="text/javascript">
<!-- 

 // Switch between regions
 function changeRegionType(form){
  // get the various elements we whish to manipulate
  var reg1 = getElementById('region_1');
  var reg2 = getElementById('region_2');

  // hide one row, show the other
  if (form['region_type'].value == 'region_1') {
   reg1.style.display = '';
   reg2.style.display = 'none';
  } 
  else if (form['region_type'].value == 'region_2') {
   reg1.style.display = 'none';
   reg2.style.display = '';
  }

  }

// --> 
</script>


<form na开发者_开发知识库me="QueryForm" action="something.php" method="get">

 <select name="region_type" onChange="changeRegionType(this.form)">
  <option selected value="region_1">Region One</option>
  <option value="region_2">Region Two</option>
 </select>

 <tr id="region_1">
  <!-- Show this row to people who want to query about region 1 -->
 </tr>

 <tr id="region_2" style="display: none;">
  <!-- Show this row to people who want to query about region 2 -->
 </tr>

</form>


Form fields remember their values over page back/forwards commands, so when you come back to the previous page, the last selected value ‘region two’ is reselected in the dropdown, but you won't get an onchange to tell you it has happened.

Consequently you should call the changeRegionType function to update the DOM from the selection, on the load event. ISTR some browser (Opera?) actually does the form update just after onload, so it may pay to fire the function on a 0-timeout in the onload instead.

You're not seeing the same in Firefox due to the bfcache. This keeps the previous page when you leave it, just not displayed. When you go back to it, it can un-hide the existing page DOM as if it had never been left. (This is done to increase the speed of back/forward navigations.) When the bfcache is disabled or your page falls out of it due to other pages crowding it out, you'll see the same behaviour as in IE and the other browsers. (Safari 4 now also has a similar bfcache feature.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜