Theodore Steiner Theodore Steiner - 3 months ago 17
HTML Question

Alerting JS Array Selection

I have a select with options that I am putting into an array, and I am attempting to alert a specific message when you click a button, but only if the proper array[x] has been selected. However, when I click the button, regardless of the option I get the message. What am I doing wrong?

Code:

HTML:

<button id="button">Click Me</button>
<br />
<br />
<select id = "list" value = "list">
<option id="one" value="one">
one
</option>

<option id="two" value="two">
two
</option>

<option id="three" value="three">
three
</option>
</select>


JS:

var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list").selectedIndex;

for (var i = 0; i < list.options.length; i++) {
listArr[i] = list.options[i].value;
}

button.onclick = function() {
if (selected = [1]) {
alert("hello");
}
};

Answer

You cannot compare arrays like this. You need to use literal number instead. JSFiddle

var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list");

for(var i = 0; i < list.options.length; i++) {
  listArr[i] = list.options[i].value;
}

button.onclick = function() {
  if(selected.selectedIndex == 1) {
    alert('hello');
  }
};
Comments