I am trying to learn HTML and have run into a problem that shows I must fundamentally misunderstand something about how this keyword works.
I am using a select to display a relevant image (when one of two options is selected the image should show). The code I have looks like this:
<select onchange="document.getElementById('preview').src = document.getElementById(this.id).getAttribute('data-value')">
<option id = "id1" data-value="Image1"> Image1 </option>
<option id = "id2" data-value="Image2"> Image2 </option>
</select>
<br>
<img id="preview" height="200px">
Running this code the image does not display and I get no errormessage. If I replace this.id by ‘id1’ (ie manually specify the id) the image display as expected but then the image cannot be changed by selecting option.
I could replace document.getElementById(this.id).getAttribute(‘data-value’) -> this.value, but I have reserved the value attribute for another feature.
Is there another way to do this ?
3
Answers
I’ve modified your code a bit. using the actual options in place of the
this
It will likely be better to define this
onChange
as a function outside the markup.In the event handler,
this
is the element itself, the<select>
. Also, thechange
event just doesn’t tell what you want. You could simply write aconsole.log(event)
there and check what attributes it has. Or look up in the documentation of course, https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement#events links bothchange
andinput
(it doesn’t tell the new value either).What you can do instead is using
this
, and theselectedOptions
"array":You should learn to code clean and that you do by using the right techniques.
First you should not use the
onclick
attribute in 2023 anymore but use anaddEventListener
and split JS and HTML completely apart.You don’t need to select an option within the select. The right approach is to give the option a
value
instead of adata
attribute. BY that the select value si always the value of the selected option: