3

I'm currently trying to change the default behaviour of a multiselect element, so that a user can select and deselect multiple values, without having to press the Ctrl key all the while.

I found a simple solution here, but this does not work in ie8 (because in ie, the onmousedown does not apply to option elements).

But I figured, that one could just simulate a pressed control key, whenever the mouse hovers over a multiselect:

$(document).ready(function() {
    $('select').hover(function(e) {
        var kde = jQuery.Event("keydown");
        kde.ctrlKey = true;  //something like this
        kde.keyCode = 17;    //or this - i don't know
        $(e.target).trigger(kde);        
    });
});

Why does this not work?

  • Is the Ctrl key directly being released again?
  • Is something wrong with the code?
  • Am I missing something else entirely?
Community
  • 1
  • 1
Envyrus
  • 315
  • 1
  • 3
  • 10

2 Answers2

2

You can't simulate such events by programmatically pushing keyboard buttons, just like you can't produce a capital A by simulating the shift key while the user pushes the a key on their keyboard. Besides, even if it would work it wouldn't work: on Macs you press cmd, not ctrl, to select multiple elements.

So unfortunately you'll have to drop this approach and look for other options.

JJJ
  • 32,902
  • 20
  • 89
  • 102
  • I thought that might be the case, someone said so [here](http://stackoverflow.com/questions/2267890/jquery-emulate-key-press-ctrl-and). But I thought it might still work, as this does not invoke a browser function (right?). Thanks for the answer – Envyrus Feb 22 '12 at 14:18
0

You probably need to add a check box for each of your items, rather than a multi select control.

It is easier in code to write functions which uncheck the others when a new one is selected than to prevent this default behaviour.

tonycoupland
  • 4,127
  • 1
  • 28
  • 27
  • Yes checkboxes would solve the problem with the control key. But as there are so many values in this specific select, checkboxes would be impractical for the user. Thanks anyway – Envyrus Feb 22 '12 at 14:29
  • Could you not put the very long list of checkboxes into your own scrollable div, effectively creating your own list control? – tonycoupland Feb 22 '12 at 15:32
  • While that's possible, I don't think that's better than the native control (with it's drawbacks..) – Envyrus Feb 23 '12 at 06:36