Prageeth Prageeth - 4 months ago 8
Javascript Question

Why selecte option change event can't have this and event.target to get selected value?

In select option change event, why can't we get

this
or
event.target
to get selected value instead of writing clumsy code like
$( "select option:selected" )
to get selected value?

Because I came across problem where I have to access some
data-*
attributes in option on dom when change event get fire.

Answer

From docs, When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.)

For select-change event, this refers to select element hence you can get the value using this.value or $(this).val().

To get the data-* attributes of option elements,

Use $('option:selected', this) as this will select only those options which are under the context of changed select-element(this)