1

I have a select box that uses JS to hide/show divs based on selection. The challenge I have is that when the page is reloaded it defaults to the last selection (and no associated div) rather than the default.

CSS:

#div1,#div2,#div3 {
  display: none
}

JS:

function showHide(elem) {
  if(elem.selectedIndex != 0) {
    //hide the divs
    for(var i=0; i < divsO.length; i++) {
      divsO[i].style.display = 'none';
    }
    //unhide the selected div
    document.getElementById('div'+elem.value).style.display = 'block';
  }
}

window.onload=function() {
  //get the divs to show/hide
  divsO = document.getElementById("frmMyform").getElementsByTagName('div');
}

HTML:

<form action="#" method="post" id="frmMyform">

<select name="selMyList" onchange="showHide(this)">
    <option value="">Select an option</option>
    <option value="1">Show div 1</option>
    <option value="2">Show div 2</option>
    <option value="3">Show div 3</option>
</select>

<div id="div1">This is Div 1</div>
<div id="div2">This is Div 2</div>
<div id="div3">This is Div 3</div>

</form>

I tried setting #div0 to hidden and then adding it to the list of divs but it does'nt seem to work. Also tried using jquery but this is a WordPress site and one of the plugin's interferes with this functionality. This is very close to working perfectly, but just need to resolve this weirdness.

Any ideas?

chriz
  • 1,311
  • 2
  • 16
  • 31
  • This is similar to [How do you disable browser Autocomplete...](http://stackoverflow.com/questions/2530/how-do-you-disable-browser-autocomplete-on-web-form-field-input-tag). – Greg Burghardt Apr 10 '14 at 12:39
  • autocomplete="off" did the trick. I had a feeling it was something more browser specific. I wouldn't have though to look in that direction so thanks for the tip. It works perfectly! – bridgemanusa Apr 10 '14 at 12:46

1 Answers1

1

Try to use selected attribute for option tag:

<select name="selMyList" onchange="showHide(this)">
    <option value="" selected="selected">Select an option</option>
    <option value="1">Show div 1</option>
    <option value="2">Show div 2</option>
    <option value="3">Show div 3</option>
</select>
rvandoni
  • 3,130
  • 3
  • 29
  • 43