How to select / deselect a multiple select input at each mouse click? (without Ctrl)

5

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

var numSelected = 0;
var valSelectedArray = [];

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

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

However, I would like that by clicking on an already selected it deselected.

My algorithm is pretty bad and it gives a 'blink' effect every time I click on a new option , ie it shows a just selected at the time of the click and then add the others that have already been clicked previously, that was not cool either.

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

NOTE: I DO NOT WANT TO USE ANY PLUGIN.

    
asked by anonymous 12.02.2014 / 17:14

2 answers

4

Try this:

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

With this, as soon as you press the mousedown button 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 / enabled.

For example, if the event were on a tag <a href="http://testlink.com"> , you would not be directed to a new url.

In our case, preventDefault causes the (default) action to deselect all other entries when you click an item (without Ctrl) to not execute. Note that disabling the default action also causes the item not to be automatically selected, so the requirement of this.selected = !this.selected;

More information about preventDefault here .

Proof of Concept:

link

    
12.02.2014 / 18:55
-1

John Paul, by default a <select multiple> can have multiple elements selected or deselected using ctrl + click , and also by dragging the mouse click.     

12.02.2014 / 17:46