Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 356
Prageeth godage Avatar asked Dec 18 '22 15:12

Prageeth godage


1 Answers

Pure JavaScript

If you want a pure JavaScript approach, then use the event.target. To quote the official MDN documentation...

The target property of the Event interface is a reference to the object onto which the event was dispatched. (Source: MDN Web Docs: Event.target.)

Since that gives us the element selected, all we then need is the value attribute, and getting the text display would be nothing more than event.target[event.target.selectedIndex].text...

function getSelectedValue(event) {
   console.log("Value: " + event.target.value + "; Display: " + event.target[event.target.selectedIndex].text + ".");
}
<select onchange="getSelectedValue(event)">
    <option selected disabled>--Pick an Option--</option>
    <option value="blue1">Blueberry</option>
    <option value="rasp2">Raspberry</option>
    <option value="straw3">Strawberry</option>
</select>

Using the above approach, it would be trivial to update it to add in other attributes of the selection option value, all in pure JavaScript.

jQuery

If you want a jQuery approach, then try using the :selected query term...

$("#selector").on('change', function(){
    console.log("Value: " + $(this).val() + "; Display: " + $(this).find('option:selected').text() + ".");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selector">
        <option selected disabled>--Pick an Option--</option>
        <option value="blue1">Blueberry</option>
        <option value="rasp2">Raspberry</option>
        <option value="straw3">Strawberry</option>
    </select>
like image 58
HoldOffHunger Avatar answered May 05 '23 06:05

HoldOffHunger