javascript – How to select/deselect, at each mouse click, an input select multiple? (without Ctrl)


I'm trying to make a script to select multiple options from a <select multiple> with each mouse click. So far so good, I got it and here's the code:

var numSelected = 0;
var valSelectedArray = [];

$(document).on('mouseup', '#CentroCusto_new option', function () {
    var valSelected = $(this).val();
    valSelectedArray[numSelected] = valSelected;

    for (i = 0; i < numSelected; i++) {
            $("#CentroCusto_new option[value=" + valSelectedArray[i] + "]").prop("selected", true);

However, I would like it to deselect when clicking on an already selected one.

My algorithm is very bad and it gives a 'blink' effect whenever I click on a new option , that is, it only shows one selected at the time of the click and then adds the others that have already been clicked previously, this is also not cool .

Does anyone have any idea how to increment the deselect option in my code, or else show more efficient code?



Try this:

$('select#CentroCusto_new option').on('mousedown', function (event) {
    this.selected = !this.selected;

With this, as soon as you press the mouse button ( mousedown ) on top of the element, the selected option receives the opposite of its previous state.

The event.preventDefault() causes the default action associated with that event to not be triggered/activated.

For example, if the event was about a tag <a href=""> , you wouldn't be directed to a new Url.

In our case, preventDefault causes the (default) action of deselecting all other entries when you click on an item (without Ctrl) to not be performed. Note that disabling the default action also causes the item to not be automatically selected, hence the need for this.selected = !this.selected;

More information about preventDefault here .

Concept proof:

Scroll to Top