简体   繁体   中英

<select> element and observe('click') on options to toggle option.selected

I've seen a few examples using jQuery that do what I want, but I'm developing a plugin for an application that uses the Prototype framework and would like to stick to that.

Basically, I want the functionality as if the ctrl key was always pressed. If a selected option is clicked, I want it to de-select.

Here's an example I found using jQuery: http://jsbin.com/idofa

Here's my version that doesn't work, because the event fires after the default action selects it (which results in it selecting and then immediately being unselected).

option.observe('click', function(event){
    this.selected = !this.selected;
});

I have tried adding event.stop(); and event.preventDefault(); neither of which seem to have an effect.

Thanks!

Proper answer, from comment I made above:

Selection is performed on mousedown, so 'mousedown' event has to be used instead of 'click' here.

option.observe('mousedown', function (event) {
    this.selected = !this.selected;
    event.stop();    // unnecessary in this case, but I think it's good practice
});

​ Example on a fiddle, edited by Victor:

http://jsfiddle.net/RP7em/3/

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