1

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)?

Community
  • 1
  • 1
handle
  • 5,859
  • 3
  • 54
  • 82

3 Answers3

1

as per your requirement try this

var option = document.createElement('option');
option.onmousedown = function() {
  if (this.selected) {
    this.selected = false;
    return false;
  }
  else
  {
  this.selected = true;
    return true;
  }
};
option.innerHTML = "hey, hoh, gelato!";
var select = document.getElementById("sel");
select.appendChild(option);

hope it work for you

Paarth
  • 580
  • 3
  • 10
0

OK, specifically, on Windows 7 it doesn't work with Chrome, Firefox, Opera, Internet Explorer. On Android it doesn't even look like a pulldown menu, but that's just a jsfiddle problem, nothing to do with the code. I'll try on Windows 10 later this week.

Davide Andrea
  • 1,357
  • 2
  • 15
  • 39
-1

The approach with a custom property seems to work: https://jsfiddle.net/L0L3378q/3/

HTML:

<select id="sel" size="3" multiple="multiple">
  <option>First!</option>
</select>

JavaScript:

var option = document.createElement('option');
option.myselected = false;
option.onclick = function() {
  if (this.myselected) {
    this.selected = false;
    this.myselected = false;
  }
  else {
    this.myselected = true;
  };
};
option.innerHTML = "hey, hoh, gelato!";

var select = document.getElementById("sel");
select.appendChild(option);
handle
  • 5,859
  • 3
  • 54
  • 82
  • 1
    Does not work well with multiple selections (sometimes the custom state gets "confused"). – handle Aug 04 '16 at 10:19
  • No, it does not work. @Paarth 's solution does work – Davide Andrea Nov 23 '20 at 21:27
  • @DavideAndrea Please let everyone know what OS and browser you are using. Both answers still work on "hey ho gelato" in FF 83.0 beta on Windows 10. With both items selected, the order of selection matters, and my answers then deselects both options, while Paarth's does not. – handle Nov 24 '20 at 07:45