Reputation: 529
I'm trying to make the JavaScript for a <select>
's <option>
with 2 items inside it, but I don't seem to be able to do any events once one of them are selected. Here's my code:
var e1 = document.getElementById("#selector").option[0].text;
var e2 = document.getElementById("#selector").option[1].text;
var e3 = document.getElementById("#selector").option[2].text;
document.querySelector("e1").addEventListener("click", myInfo, false);
function myInfo(){
alert("Test");
}
<select id="selector">
<option value="" disabled="disabled" selected="selected">Select a layout</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
Upvotes: 1
Views: 2501
Reputation: 68
your select element looks fine. But your code needs changes:
var selector = document.getElementById("selector")
selector.addEventListener("change", function(){
alert(selector.options[selector.selectedIndex].text);
});
This is all you need. Not to forget to mention that in your code
var e3 = document.getElementById("#selector").option[2].text;
to select by id just write 'selector' and not '#selector'. and it is called 'options' not 'option'.
I hope this helps
Upvotes: 2
Reputation:
I don't think you understand how the functions, especially querySelector
, work.
You should use change event instead:
var val;
document.getElementById("selector").addEventListener("change",function(){
val = this.value; // or document.getElementById("selector").value
// then use your value to do other things
});
p.s. Please search on the web for the use of the querySelector
method. Clearly you don't know how it works.
Upvotes: 2