简体   繁体   中英

JavaScript - using addEventListener instead of inline “onchange” with select menu

I'm trying to use "addEventListener" instead of an inline "onchange".

Something is wrong with my approach. How do I use the "addEventListener" correctly?

https://jsfiddle.net/gdfe2ynL/1/

 <select id="feedbackCategory" onchange="logvalue(this.value)"> <option value="" selected>Choose a category</option> <option value="example1">Example 1</option> <option value="example2">Example 2</option> </select> <select id="feedbackCategory2"> <option value="" selected>Choose a category</option> <option value="example1">Example 1</option> <option value="example2">Example 2</option> </select> <script> function logvalue(value) { console.log(value) } document.getElementById("feedbackCategory2").addEventListener("change", logvalue(this.value)); </script>

In the programmatic listener, the event comes through as event , the element is event.target and the value of that element is event.target.value . It's easier for this kind of thing to group the elements together with a common attribute, like class and then apply the listener to each one of them via querySelectorAll and a forEach loop

 function logvalue(event) { console.log(event.target.value + ' selected from the #' + event.target.id + ' element') } window.addEventListener('DOMContentLoaded', () => { document.querySelectorAll(".fbselect").forEach(el => el.addEventListener("change", logvalue)) })
 <select class='fbselect' id="feedbackCategory"> <option value="" selected>Choose a category</option> <option value="example1">Example 1</option> <option value="example2">Example 2</option> </select> <select class='fbselect' id="feedbackCategory2"> <option value="" selected>Choose a category</option> <option value="example1">Example 1</option> <option value="example2">Example 2</option> </select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM