Prageeth Prageeth - 3 months ago 6
Javascript Question

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

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

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
attributes in option on dom when change event get fire.


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 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)