Jquery multiple select box
swentel - June 24, 2007 - 22:40
Hi,
I've been working on a small jquery feature which makes multiple select boxes a bit smarter. If you click without using the CTRL button, the jquery remembers your previous clicked options. I'm posting the code here to see if this is good enough and also if anyone has an idea to capture an allready selected option when you click on it (I know i could use this.options[this.selectedIndex]), so this becomes unselected. The workaround for now is to press CTRL, click on the selected option and move your mouse pointer out of the selection box, but this isn't ideal in my opinion. Maybe we could get this into Javascript tools, or maybe into core, because it's a feature I really like nowadays.
if (Drupal.jsEnabled) {
$(document).ready(function() {
var selected = new Array();
// load all selected options in array when the mouse pointer hovers the select box
$('select').mouseover(function() {
if (this.multiple == true) {
for (var i=0,a=0;i<this.options.length;i++) {
if (this.options[i].selected == true) {
selected[a] = this.options[i].value;
a++;
}
}
}
});
// safe them when you click the mouse
// note, the click function also triggers this event, but I'm not sure which one is best ?
$('select').change(function() {
// make sure it's a multiple select
if (this.multiple == true) {
for(var i=0;i<selected.length;i++) {
for(var a=0;a<this.options.length;a++){
if (selected[i] == this.options[a].value) {
this.options[a].selected = true;
}
}
}
}
});
});
}
I've altered the code a bit
I've altered the code a bit and have set up a test-page. It should be fully working now. See http://realize.be/drupal-multiple-select-jquery-test
Thanks swentel for your
Thanks swentel for your great work. However I tested the demo and it seems not quite working in IE7?
IE7 Fix
There is a bug in IE7 which means that the mouseover event is only triggered again once the mouseover trigger has evaluated to false...i.e. the mouse pointer has left and returned to the form field. This means that the saved multiple selects aren't being reloaded into the field...the following code corrects this:
if (Drupal.jsEnabled) {
$(document).ready(function() {
var selected = new Array();
// safe them when you click the mouse
$('select').click(function() {
// make sure it's a multiple select
if (this.multiple == true) {
for(var i=0;i<selected.length;i++) {
for(var a=0;a<this.options.length;a++){
if (selected[i] == this.options[a].value && this.options[a].selected == true) {
this.options[a].selected = false;
selected.splice(i,1);
} else if (selected[i] == this.options[a].value) {
this.options[a].selected = true;
}
}
}
}
// load all selected options in array when the mouse pointer hovers the select box
if (this.multiple == true) {
for (var i=0,a=0;i<this.options.length;i++) {
if (this.options[i].selected == true) {
selected[a] = this.options[i].value;
a++;
}
}
}
});
});
}