Capture Option data on Select Change

Capture Option data on Select Change

Replacing deprecated with this.selectedIndex

Sometimes we want to 'listen' to an event change of the select element. Especially when the option is changed - and get the newly selected value and store it elsewhere. For this we use onchange on the select element and not on the option element.

There are 2 ways to get the selected option's value, I'll show both, the first one being deprecated but still works but has been Legacy’d into standarization for the window object.


  2. this.selectedIndex

The event object is part of window object which should be window.event but browsers may drop support for it in the future. Instead use this.selectedIndex.


<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />  
    <meta http-equiv="Cache-control" content="no-cache">  
    <title>capture option data on select change</title>
    <link href="" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <div class="container d-flex flex-column">
        <h3 class="mb-3">User</h3>
        <div class="input-group mb-3">            
                document.querySelector('#user-email').value = this[this.selectedIndex].getAttribute('data-email');
                document.querySelector('#user-mobile').value = this[this.selectedIndex].getAttribute('data-mobile');
                <option selected>Select a User</option>
                <option value="1" data-email="" data-mobile="6666666666">John Matthews</option>
                <option value="4" data-email="" data-mobile="8888888888">Harry Smith</option>
                <option value="5" data-email="" data-mobile="3333333333">Donald More</option>
                <option value="19" data-email="" data-mobile="1111111111">Agent Smith</option>
                <option value="20" data-email="" data-mobile="9898989898">Bruce Kennedy</option>
        <div class="mb-3">
            <input type="text" name="user-email" id="user-email" class="form-control" placeholder="Email" disabled />
            <input type="text" name="user-mobile" id="user-mobile" class="form-control" placeholder="Mobile" disabled />

Demo :