I want select element to contain one default option that shows a popup when selected. So I've created HTMLOptionElement and add an event to onclick event listener but the event doesn't trigger when the option is clicked.
Here is my code:
const selectDefaultOption = new Option(".. show popup ...");
selectDefaultOption.addEventListener("mouseup", () => {
// ... show pop up
});
document.querySelector("#select").appendChild(selectDefaultOption);
Am I doing something wrong? Or it's not possible to achieve what I'm trying to.
You would put the listener on the select element and check for the value (rather than put a listener on the option element directly)
document.querySelector('select').addEventListener('change', e => { if (e.target.value === '2') console.log('The special option was chosen'); })
<select> <option value='1'>1</option> <option value='2'>Special</option> <option value='3'>3</option> </select>
Your code working. with mouseup
The mouseup event is fired at an Element when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is located inside it.
https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseup_event
const selectDefaultOption = new Option(".. show popup..."); selectDefaultOption.addEventListener("mouseup", () => { alert() }); document.querySelector("#select").appendChild(selectDefaultOption);
option { width: 200px; background: gray; }
<div id="select"> <option>123</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.