3

I have this function displaySelectedUser, so I want to Set displaySelectedUser as a change event listener for the <select></select> UI element using only the DOM Selector API.

this is the code that I have tried out:

<body>
<div class="select">
      <select class="select-text">
        <option disabled selected>Select User</option>
         <option>user 1</option>
         <option>user 2</option>
      </select>
</div>
<body>
<script>
   const displaySelectedUser = () => {
 //some code...
};
    document.querySelector('select').change = displaySelectedUser;   
  };
</script>
b0nbon
  • 96
  • 2
  • 9

3 Answers3

1

Try this using the HTML5 Selector API.

 document.querySelector(".select").addEventListener("change", displaySelectedUser)
electrode
  • 473
  • 6
  • 13
0

You can simply add an onChange event handler on the select element which calls that function directly.

<body>
<div class="select" onChange="displaySelectedUser()">
      <select class="select-text">
        <option disabled selected>Select User</option>
         <option>user 1</option>
         <option>user 2</option>
      </select>
</div>
<body>
<script>
   const displaySelectedUser = () => {
 //some code...
};
</script>
Tim Smith
  • 56
  • 2
0

As Tim has mentioned you can simply add onchange instead of change in your code and it woks.

<body>
<div class="select">
      <select class="select-text">
        <option disabled selected>Select User</option>
         <option>user 1</option>
         <option>user 2</option>
      </select>
</div>
<body>
<script>
   const displaySelectedUser = () => {
 //some code...
     alert('calling')
};
      const powerupTheUI = () => {
    document.querySelector('select').onchange = displaySelectedUser;   
  };
  
  powerupTheUI();
</script>
vsoni
  • 497
  • 1
  • 7
  • 22