-1

I'm makin a select with the multiple property enabled.

<select id="lst_prueba1" size="8" multiple>
    <option>Alderaan</option>
    <option>Corellia</option>
    <option>Endor</option>
    <option>Kashyyyk</option>
    <option>Mustafar</option>
    <option>Naboo</option>
    <option>Nar Shaddaa</option>
    <option>Tatooine</option>
    <option>Yavin</option>
</select>   

But i want to select the options without the need of pressing the ctrl key. Is there a way to fake the press using javascript or what could in the onchange event?

The answer provided here didn't work for me: How to avoid the need for ctrl-click in a multi-select box using Javascript?

Community
  • 1
  • 1

1 Answers1

2

Although I'd suggest using checkboxes as mentioned in the comments, this should do the trick. Works in Chrome, Firefox and Edge. Might want to test more depending on your requirements.

<script>
    var selected = {};

    $("#lst_prueba1").click(function(e) {

        var options = this.options;
        var option;
        var value;

        value = $(this).val();

        for (var i = 0; i < options.length; i++) {
            option = options[i];

            if (option.value == value) {
                selected[value] = !selected[value];
            }

            option.selected = !!selected[option.value];
        }
    });
</script>
Michael Hommé
  • 1,696
  • 1
  • 14
  • 18