0

so I am working on a project and I need to take the value of a select menu. However, when I do, I get the error TypeError: Cannot read property 'options' of null. Hopefully you guys can help? Here is my HTML code for the select menu:

<div id="MetalTypeSect">
  <h2><a id="MetalType"></a>Metal Type</h2>
    <select id="select1">
      <option value="blank">--Select--</option>
      <option value="Alum">Alum. 5052</option>
      <option value="GalvL">Galvaneal</option>
      <option value="CRS">CRS</option>
      <option value="SST">SST304</option>
      <option value="GalvZ">Galvanized</option>
    </select>
</div>

and here is my js code

var metalTypeSelectedValue = document.getElementById("select1");
var metalType = 
metalTypeSelectedValue.options[metalTypeSelectedValue.selectedIndex].value;

while(true) {
  if(metalType == "blank") {
    document.getElementById("AlumThickness").style.visibility="hidden";
  }
}

The error says its on line 2 of the js code. Help!

Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Sebastian Simon Aug 10 '18 at 14:33
  • 2
    Wait for the DOM to be loaded before accessing it. Also, `while(true)` will produce an infinite loop once the DOM issue is resolved. – Sebastian Simon Aug 10 '18 at 14:34
  • At the moment you're doing `var metalTypeSelectedValue = document.getElementById("select1");` no element with that `id` exists. – connexo Aug 10 '18 at 14:42

1 Answers1

0

Use onchange() event. Like this

<select id="select1" onchange="myFunction()">

Then get value in your js function

function myFunction() {
    var metalType = document.getElementById("select1").value;

    if(metalType == "blank") {
        document.getElementById("AlumThickness").style.visibility="hidden";
    }
}
wizbiz
  • 28
  • 5