1

I have the following elements, each one is the id of a select element which will have a dynamically generated dropdown list:

const year = document.getElementById('year');
const brand = document.getElementById('brand');
const version = document.getElementById('version');
const model = document.getElementById('model');

I have the following handle function which I would like to reuse for every single one of them:

function handleChange() {
    let selected = year.options[year.selectedIndex].text;
    console.log(selected);
}

year.addEventListener('change', handleChange);

So far that is working but idk how to make handleChange() take the id of the SELECT element. I tried the following code but it's not correct.

function handleChange(e) {
    let id = e.target.id;
    let selected = id.options[id.selectedIndex].text;
    console.log(selected);
}

I'm trying to stay away from JQuery on this one.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
szter
  • 53
  • 5
  • 1
    `this` should refer to the element already, no need to go looking for stuff by id. But if you are explicitly accessing the _id_, that id course doesn’t have any `options` property, it is pure text. – CBroe Mar 15 '18 at 15:56

1 Answers1

1

You just need to use this inside the change event callback function, in your case the handleChange function.

This is how should be your code:

function handleChange() {
  let selected = this.options[this.selectedIndex].text;
  console.log(selected);
}

Demo:

const year = document.getElementById('year');

year.addEventListener('change', handleChange);

function handleChange() {
  let selected = this.options[this.selectedIndex].text;
  console.log(selected);
}
<select id="year">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • works perfectly! I was quite convinced I needed to get the id of the element for this to work... – szter Mar 15 '18 at 16:32
  • @szter Why would you get the `id`? If you get it you need to fetch back the element with `getElementById()` again, this is too far complicated. – cнŝdk Mar 15 '18 at 16:34