HTML javascript select action

34,891

You really should probably bind this logic to the onchange event of the select itself, and not the click event of the individual options:

var myDiv = document.getElementById("myDiv");
document.getElementById("mySelect").onchange = function(){
  myDiv.style.display = (this.selectedIndex == 0) ? "block" : "none";
}

When we bind it this way, we don't need to mix our HTML and our Javascript. Our HTML can look as simple as what follows:

<select id="mySelect" name="values">
  <option>0</option>
  <option>1</option>
  <option>2</option>
</select>
<div id="myDiv">
  <p>Select 0 to show me, otherwise I'm invisible!</p>
</div>

Online demo: http://jsbin.com/ijogi

Share:
34,891
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I got a selection list:

    <select>
    <option value="0" onclick="anders('1')">Anders</option>
    <option value="200" onclick="anders('');" selected="selected">&#8364; 200,-</option>
    <option value="300" onclick="anders('')">&#8364; 300,-</option>
    <option value="400" onclick="anders('')">&#8364; 400,-</option>
    <option value="500" onclick="anders('')">&#8364; 500,-</option>
    </select>
    

    When I select value "0" something need to be visible, this is working in firefox but not in internet explorer. Even an alert function with onclick isn't working in IE, does anybody knows something for this?

  • Sampson
    Sampson about 14 years
    @Stefan: Remember to try and keep your Javascript as far removed from your HTML as possible :)
  • Sampson
    Sampson about 14 years
    @stefan: Change this.value to this.selectedIndex.