Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unselect an option from a multi select on a click ONLY if it is selected

I have a multi select element and once I select an option on it, is it then impossible to unselect all the options. I need to unselect the option when I click it and it was previously selected.

I have tried a few things but they don't work because everytime i click the option it becomes selected whether it was or not so its impossible to know if it was previously selected and should be unselected or if its the first time i am clicking it to select it

http://jsfiddle.net/JRgdv/

<select  multiple="multiple">
    <option>11111</option>
    <option selected>2</option>
    <option>33333</option>
    <option>44444</option>
</select>

I know I can have button or an area that i can click to clear the whole thing but i am truying to make it so that if you click a selected option then it unselects it

edit: CTRL+Click is not what i am looking for. it has to be with the mouse only

like image 766
code511788465541441 Avatar asked May 22 '13 16:05

code511788465541441


People also ask

Is it possible to deselect an option from a single select dropdown box?

We can deselect an option from a static dropdown with the help of methods under Select class. deselect_by_value(args) − Deselection with the help of value of option. This method deselects the option based on the value of the specific option.

How do you unselect an option in HTML?

The Select remove() method in HTML DOM is used to remove an option from a drop-down list.


2 Answers

Could be a workaround:

SEE DEMO

$('select option').on('mousedown', function (e) {
    this.selected = !this.selected;
    e.preventDefault();
});

EDIT: this doesn't work on IE (version???). For cross browser solution, even uggly, try that instead: https://stackoverflow.com/a/21797607/1414562

like image 180
A. Wolff Avatar answered Nov 04 '22 10:11

A. Wolff


This may be a little hack-ish, but it works. Demo: http://jsfiddle.net/tymeJV/JRgdv/1/

var currentSelect = $("select option:selected").index();

$("select option").click(function() {
    if ($(this).index() == currentSelect) {
        $(this).prop("selected", false);
        currentSelect = -1;
    } else {
        currentSelect = $(this).index();
    }
});
like image 24
tymeJV Avatar answered Nov 04 '22 11:11

tymeJV