Error with getting html select value into js variable

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Error with getting html select value into js variable



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!





Possible duplicate of Why does jQuery or a DOM method such as getElementById not find the element?
– Xufox
Aug 10 at 14:33





Wait for the DOM to be loaded before accessing it. Also, while(true) will produce an infinite loop once the DOM issue is resolved.
– Xufox
Aug 10 at 14:34


while(true)





At the moment you're doing var metalTypeSelectedValue = document.getElementById("select1"); no element with that id exists.
– connexo
Aug 10 at 14:42


var metalTypeSelectedValue = document.getElementById("select1");


id




1 Answer
1



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";







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard