1

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>

8
  • 1
    This is much easier if you use the jQuery library. Is that an option for you? Commented Feb 10, 2017 at 14:35
  • Can you tell us what problem you're trying to solve? And, further, document.querySelector("e1") is looking for an element <e1>, whereas you're probably - or should be - looking to find the <select> element, with either document.getElementById('selector'); or document.querySelector('#selector') Commented Feb 10, 2017 at 14:36
  • 1
    @GentlemanMax it's not the question, he's asking for Js solution. Before use Jquery it's better to learn JS before Commented Feb 10, 2017 at 14:36
  • 1
    @Alexis, that's why it was a comment instead of solution. I would also tend to disagree with the idea that you need to master JS before jQuery in most situations regardless, though this is hardly the place to discuss it. Commented Feb 10, 2017 at 14:39
  • 1
    @GentlemanMax, not everything needs jQuery. there is no need to add a massive library to make things "easy" when if you actually learned js, this is easy anyway Commented Feb 10, 2017 at 14:40

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.