Pergunta

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>
Foi útil?

Solução

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);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top