Prageeth Prageeth - 4 months ago 9
Javascript Question

Why select 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 ?

Answer

$("select").on('change', function(){
  console.log($(this).val());
  console.log($(this).find('option:selected').attr('data-attribute')); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
  <option data-attribute="a">1</option>
  <option data-attribute="b">2</option>
  <option data-attribute="c">3</option>
  <option data-attribute="d">4</option>
</select>

Comments