简体   繁体   中英

javascript document.getElementById is not working

Do you know why this easy javascript is not working? It is working in Firefox, Chrome isnt working in IE Safari and Opera. Can you help me? It seems to document.getElementById has some problem in IE, Safari and Opera. Why?

   <form name="formular" action="test.php">
      <select id="testMenu" name="testMenu" onChange="testOptions()">
        <option id="X2" value="2">2</option>
        <option id="X3" value="3" selected>3</option>
        <option id="X4" value="4">4</option>                        
      </select>     

      <select id="nextMenu" name="nextMenu">
        <option id="B1" value="1">B1</option>
        <option id="B2" value="2">B2</option>
      </select>
   </form>
     <script type="text/javascript">
       var choose_option =3;

       function testOptions() {
       var choose_option = document.getElementById("testMenu").selectedIndex+2;

       if (choose_option == 4){
          document.getElementById("B2").style.display="none";
        }else{
          document.getElementById("B2").style.display="block";  
        }
    }   
    </script>

Why do you think getElementById , specifically, isn't working? The problem is more along the lines of not being able to apply display: none to <option> elements. The easiest fix would probably be to set disabled for it:

document.getElementById("B2").disabled = choose_option === 4;

If you want it to really be gone, that would be done by removing it:

var nextMenu = document.getElementById("nextMenu");
var b2 = document.getElementById("B2");

function testOptions() {
    var choose_option = document.getElementById("testMenu").selectedIndex + 2;

    if (choose_option === 4) {
        if (b2.parentNode) {
            b2.parentNode.removeChild(b2);
        }
    } else if (!b2.parentNode) {
        nextMenu.appendChild(b2);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM