Reputation: 29
I'm working on a project for class, and I have a dropdown box with the id of "idSelect." But when I try to grab the value of the dropdown box into a variable, it says that idSelect
isn't defined.
I tried changing the name of the id, but the same thing happened. If I try to console.log(idSelect.value)
, it shows up as whatever I have selected, but it still shows an error that idSelect
is not defined.
This is in the head tags & script tags
var selectedHero = idSelect.value;
This is in the body tags
Change your avatar:
<select id="idSelect">
<option>Batman</option>
<option>Spider-Man</option>
<option>Iron Man</option>
<option>Superman</option>
<option>Wolverine</option>
</select>
The variable selectedHero
should store whatever the player has selected in the dropbox such as "Iron Man" or "Superman," but instead in the Inspect element all it says is this:
Monster Project (BLANK).html:22 Uncaught ReferenceError: idSelect is
not defined
at file:///C:/Users/chim%20chimoi/Desktop/Ifra/APCOMSCI/Monster_Project_HOME/Monster%20Project%20(BLANK).html:22:22
This worked before and I didn't change anything, but when I ran it again this error just started popping up.
Upvotes: 1
Views: 523
Reputation: 821
Most probably there was a variable "idSelect" which does not exist, or is not accessible at the point you are referencing it.
Try making it global:
<script>
window.idSelect = document.getElementById('idSelect');
</script>
or reference it like this every time you need it:
<script>
var idSelect = document.getElementById('idSelect');
var selectedHero = idSelect.value;
</script>
Upvotes: 0
Reputation: 1434
You are passing a HTML's id into Javascript, and in Javascript there's no such variable idSelect being declared, e.g.:
var idSelect;
But even if you declare it in Javascript, the way to pass the HTML's value into Javascript is not correct.
If you want to keep the same variable name, you can do this:
var idSelect = document.getElementById('idSelect').value;
Upvotes: 1