3

I am using the code which is written in this stackoverflow post

How to avoid the need for ctrl-click in a multi-select box using Javascript?

it is recommended also in many other articles, to do multiple selection without ctrl-click.

the code:

$('option').mousedown(function(e) {
    e.preventDefault();
    $(this).prop('selected', !$(this).prop('selected'));
    return false;
});

The problem is that the code is not working on FireFox 31.0. you can try it using the following link

FIDDLE

does anybody know a work around for this problem :)

Community
  • 1
  • 1
user3584625
  • 239
  • 1
  • 3
  • 9

1 Answers1

1

The below code works in firefox 31.0,IE 10 and crome 36.0.1985.143. But it dose not work well if CTRL keys is used also.

 $('select').bind("click", function (event, target) {

        event.preventDefault();
        var CurrentIndex = event.target.selectedIndex==undefined? $(event.target).index(): event.target.selectedIndex
        var CurrentOption = $("option:eq(" + CurrentIndex+ ")", $(this));
        if ($(CurrentOption).attr('data-selected') == undefined || $(CurrentOption).attr('data-selected') == 'false') {
            $(CurrentOption).attr('data-selected', true);
        }
        else {
            $(CurrentOption).prop('selected', false).attr('data-selected', false);
        }

        $("option", $(this)).not(CurrentOption).each(function (Index, OtherOption) {
            $(OtherOption).prop('selected', ($(OtherOption).attr('data-selected') == 'true') ? true : false);
        });
         return false;
    });
Priyank
  • 1,353
  • 9
  • 13
  • You can test if the ctrl or meta key is pressed. Also I believe it is `.on` and no longer `.bind` – mplungjan Sep 02 '14 at 12:09
  • thank you for your comment, There is a simple problem but i dont know where. if the select started with some selected options like this: and now if you try to select other options, it always clears the already selected ones. – user3584625 Sep 02 '14 at 13:31
  • @user3584625 I have used a custom attribute data-selected to track its state so you need to maintain that attribute also. So when you are making the option already selected, set the attribute also to true. – Priyank Sep 03 '14 at 04:40
  • It did not work in IE 11. Can't select multiple values – dipanshu Jan 27 '16 at 07:44