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
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.
The Select remove() method in HTML DOM is used to remove an option from a drop-down list.
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
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With