HTML <select>
<option>
s are selected by mouse click. Multiple selections are possible by CTRL+click or mouse click+drag. Deselection is possible by CTRL+click.
I would like to allow deselection of a previously selected option by clicking on it again. Any click then would toggle the selection.
var option = document.createElement('option');
option.onclick = function() {
if(this.selected) {
this.selected=false;
};
};
https://jsfiddle.net/L0L3378q/1/
Unfortunately, it seems that onclick
is evaluated after the browser (Firefox in my case) handles the click itself, which results in "select" followed immediately by the "deselect" of my onclick function.
Now it would seem that all the browser does every time is "select" the option on click, which would render the function useless, if it never gets the actual selected state.
Is there a way to ensure that onclick is evaluated first, the brower's click is suppressed, or that the selected state can be tracked independently (custom property)?