jQuery MultiSelect

Improve multi-select form controls with this easy-to-use jQuery plugin.

Contents

Overview

jQuery MultiSelect is a configurable plugin for jQuery. It is designed to turn ordinary multi-select form controls into user-friendly dropdown lists. Check out the demo to see an example.

This project was inspired by arco90’s MultiSelect tool, but was written entirely from scratch to make it easier to implement, more accessible, and to shorten the code length.

This project is in beta testing and may not be ready for production use yet! See the to do list for more information.

Features

Compatibility

This plugin requires jQuery 1.2.6 or above and has been tested to work in the following browsers:

Demo

View a live demonstration of jQuery MultiSelect.

Download

Current version: Version 1.0.2 beta (10 May 2009)

This plugin is provided to you as-is, at absolutely no cost. If you would like to support its development, feel free to contribute any amount you prefer via PayPal. As always, you are welcome to contribute code for bug fixes and feature enhancements as well. Either way, thanks for supporting our efforts!

Usage

Creating

In it’s simplest form, you can create a MultiSelect form control using the following code:

$(document).ready( function() {
    $("#control_id").multiSelect();
});

where #control_id is the ID of the select element that exists on your page. You can use any valid jQuery selector as the ID, but make sure you only use select elements with the multiple="multiple" attribute to get the expected results.

Configuring

Parameters are passed as an object to the multiSelect() function. Valid options include:

ParameterDescriptionDefault Value
selectAllwhether or not to display the “Select All” optiontrue
selectAllTexttext to display for selecting/unselecting all options simultaneouslySelect All
noneSelectedtext to display when there are no selected items in the list'Select options'
oneOrMoreSelectedtext to display when there are one or more selected items in the list (note: you can use % as a placeholder for the number of items selected). Use * to show a comma separated list of all selected items'% selected'

To create a MultiSelect control with multiple parameters, your code will look something like this:

$(document).ready( function() {
    $("#control_id").multiSelect({
      selectAll: false,
      noneSelected: 'Check some boxes!',
      oneOrMoreSelected: '% options checked'
    });
});

Styling

The MultiSelect plugin relies 100% on CSS for styling. To give your users an aesthetically pleasing experience, you should either use the included stylesheet or create your own. Refer to jquery.multiSelect.css to make any changes in the styles.

Callback

If you specify a callback function, the MultiSelect control will execute it whenever a checkbox’s checked state is changed. Currently, the function passes the checkbox element that was clicked as a jQuery object. To specify a callback function, your code will look something like this:

$(document).ready( function() {
    $("#control_id").multiSelect(options, function() {
        alert('Something was checked!');
    });
});

where options is either null or a JavaScript object (see configuring for details).

To Do List

As jQuery MultiSelect is still in beta testing, there is an actively-updated to do list. To add something to the list or to contribute to the project in any way, please contact me using our contact form. You will receive appropriate credit for any and all contributions you make to this project, however you must agree that all code you submit will fall under the same license as the jQuery MultiSelect project.

What’s Left?

Known IE6 Differences

Licensing & Terms of Use

This plugin is dual-licensed under the GNU General Public License and the MIT License and is copyright 2008 A Beautiful Site, LLC.

Comments

Slick stuff! My question: is there a way to list the items selected instead of 'x Selected' ie it would show 'Option 1 + Option 2 + Option 3 etc'...

Jason on May 2nd, 2008

Have you seen this: http://lovcombo.extjs.eu ?

Dezo on May 4th, 2008

Jason: there is now! Check out the demo to see it in action. Details on how to implement this feature are in the 'Configuring' section.

Cory S.N. LaViska on May 5th, 2008

Is there a way to use this as a list box with the size="6"?

Jon on May 22nd, 2008

css textboxt ınput (textfield) style - examples - -
http://www.css-lessons.ucoz.com/textbox-css-examples.htm

chester on May 23rd, 2008

about css parameters...
http://css-lessons.ucoz.com/css-parameters.htm

sezer on Jun 3rd, 2008

Thanks for a great script, but please be aware that in the Multiple Parameters example above you haven't closed the document.ready function.

Cheers!

Paul on Jun 16th, 2008

Thanks, Paul. Actually, I managed to forget to close out all of the examples. Fixed now :)

Cory S.N. LaViska on Jun 16th, 2008

No problem! Seeing as you're clearly better at jquery than I am, any chance you could provide some help?

I'm trying to add an onclick event that takes the ID of the clicked <option> element and uses the jquery post method to obtain records from a database and returns html which will be placed into another element on the page.

However, as soon as I add the following code, the functionality of your script ceases to work. Any ideas?!

Any help would be MUCH appreciated!

$("#baselists").multiSelect(options,
function(){
$.post("final_list.php",
{ id: $(this).val(); },
function(data){
$("#final_list").html(data);
}
)
});

Paul on Jun 17th, 2008

A very useful component!

I'm trying to do something similar to Paul, i.e. capturing the option that is selected/unselected and I had some problems that I could only resolve through changing the source of jqueryMultiselect.js.

When I created a multi selectbox using the following code:

$('.multiselect').multiSelect( null, function(el) {
alert("Option Clicked: " +el.value);
});

I would get 'Option Clicked: undefined' as the result. It seems as if an unknown object is being passed back. In order to fix this I changed the source of the multiselect method on lines 98, 172, 183 and 189 so the callback is passed 'this' rather than '$(this)'. By doing this the callback method is passed an HTMLInputObject and so the call to el.value returns correctly.

Is this the correct approach or is there a way to get at the selected option and interrogate it's properties?

Andrew Dyer-Smith on Jul 5th, 2008

You have got a fantastic script. Thank you for the same, I have searched all over google and tried to crack into website but no use. Please tell what multi-select tools have these guys used on www.monstertemplates.com

Natesh on Jul 14th, 2008

@Natesh: looks like it's a custom DIV that pops up when the "dropdown" is clicked. It's not very hard to do and you don't really need a plugin to do it.

Cory S.N. LaViska on Jul 14th, 2008

First off, thanks very much - this was just what I was looking for. I've been playing with various dropdown/combobox/SELECT element plugins and hacks for days, but this one hits the nail on the head. I wasn't looking exclusively for multi-select capability, but I'll be using this to replace both standard single-select and multi-select form controls.

In case you're interested, I made some very small changes to the source to implement the following:

- exclusive (one-at-a-time) option selection
- passing of additional CSS classes for the INPUT and option DIV elements (order of precedence over multiSelect.css is naturally determined by the order the files are linked)

I found the additional CSS support very helpful in bringing the formatting in line with my existing form controls, and to make it easier to make global changes to all controls.


-----------

// New parameters:

/*

selectExclusive - only allow one item to be selected at a time; true/false, default = false

inputClass - name of css class to be applied to created INPUT element; this will be used in addition to the standard 'multiSelect' class (useful if you'd like to inherit existing formatting rather than modifying multiselect.css)

optionsClass - name of css class to be applied to created options DIV element; this will be used in addition to the standard 'multiSelectOptions' class

*/

// Added / changed code:

// line 40: added defaults
if( o.selectExclusive == undefined ) o.selectExclusive = false;
if( o.inputClass == undefined ) o.inputClass = '';
if( o.optionsClass == undefined ) o.optionsClass = '';

// line 44 & 45: changed to support override classes
var html = '<input type="text" readonly="readonly" class="multiSelect' + (o.inputClass ? ' ' + o.inputClass : '') + '" value="" style="cursor: default;" />';
html += '<div class="multiSelectOptions' + (o.inputClass ? ' ' + o.inputClass : '') + '" style="position: absolute; z-index: 99999; display: none;">';

// line 94: inserted support for selectExclusive on click event
if (o.selectExclusive){
$(this).parents('.multiSelectOptions').find('input:checked[value!=' + $(this).attr('value') + ']').attr('checked', false);
}

// line 185: inserted support for selectExclusive on Space and Enter keypress events
if (o.selectExclusive){
$(this).next('.multiSelectOptions').find('input:checked').attr('checked', false);
}

------------


Thanks again!

Nathan Smith on Jul 16th, 2008

How to capture the data from control_7[] into a sendmail.php action script. The script does not read this at all.

But it works fine with control_3, control_4

Natesh on Jul 28th, 2008

I have added a parameter iType to decide if the selectbox items are checkbox or radio.. Simply replaced all the checkbox references with the paramater and detected if it was a checkbox for the selectAll option (which should not be there if it is a radio list). Hope it makes sense

Gary on Aug 22nd, 2008

Great plugin! I'm really glad to see this, the jQuery world needs a good multi-select plugin.

One thing I would suggest changing is the way you call the callback method.

Currently you do:
if( callback ) callback( $(this) );

I would suggest:
if( callback ) callback.apply( this , [this]);

This would make it parallel how jQuery does it's own internal callback methods and also follow a more traditional way for jQuery plugins to handle callbacks. The benefit is the context of the function, where with the way I propose you can access "this" and it refers to the DOM node being dealt with.

FWIW... I might also consider expanding the paramters, the example above only passes the element in, but you could also pass the select box as a second optional parameter as well.

Anyhow, tossing it out there... keep up the good work, and thanks for the great plugin!

Pax,
Stan

Stan on Aug 22nd, 2008

I am new to jquery, How do i populate this dropdown with ajax return data

rav on Aug 22nd, 2008

@rav: good question. This isn't built into the plug-in (yet?), so you'd really have to the code to get it to work.

Alternatively, you could create a SELECT element on the fly, populate it, and then run .multiSelect() on it. I'll have to think about that for feature enhancements.

@Stan: thanks for your insights. I'll definitely keep them in mind (as well as some other improvements) for the next version.

@Gary: thanks for the tip :)

Cory S.N. LaViska on Aug 24th, 2008

Pretty cool script but can't make it work with ASP.NET / C#

When I apply it to my ASP DropDownList it works, shows up and everything.. but when I submit I only get the first selected item... I figured I'd try with a ListBox... same thing happens! and yes I set multiple=multiple on the dropdown and selectionmode=multiple on the listbox..

can't get the data :( Any help?

thx

Mike on Aug 27th, 2008

Excellent plugin - It is really great for our complex searches.

One problem that our users have is that it sometimes fails to collapse. If you drop down the options, hover over the options and then move the mouse out of the control by passing it across the input box, it does not collapse. Our uses got frustrated when a click elsewhere on the page did not collapse the box.

I hacked it with this code. I do not have any other document level click handlers, so I can safely unbind them all. Your mileage may vary.


// Hide the dropdown
multiSelectOptionsHide: function() {
$(this).removeClass('active').next('.multiSelectOptions').hide();
$(document).unbind('click');
},

// Show the dropdown
multiSelectOptionsShow: function() {
// Hide any open option boxes
....
$(document).click( function(ev) {
// If the click is within the option list, only one extended, so ignore
var container = $(ev.originalTarget).parents('.multiSelectOptions');
if (container.length == 0) {
$(multiSelectCurrent).multiSelectOptionsHide();
$(multiSelectCurrent).unbind("hover");
}
});
},


Kevin on Sep 18th, 2008

The above problem and solution are firefox specific.

Kevin on Sep 18th, 2008

Great plugin, looking forward to the next version.

I had a problem with the placement of the div that drops down, the position it got was calculated from the left and top of the document, while the absolute positioning positioned it with those values from the containing div.

I solved it by adding a 'containingDiv' parameter, and where it set the positioning on the div i also fetched the position of the containing div and subtracted its values from the position values of the drop down div and it works.

Fredrik on Sep 25th, 2008

I don't believe dimensions is needed anymore as it's built into jquery. Why and...

var offset = $(this).offset();

needs to be changed to:

var offset = $(this).position();

James on Oct 3rd, 2008

Hi,

Would this be very easy to use as a list box instead of a combo box. I love the functionality but I need it to stay up all the time so that the options are always visible.?

I'm a very inexperienced coder so apologies if it's an obvious question.

Ben on Oct 11th, 2008

Hi,

Thanks for the multi select plug-in.
Could you please help me to get the selected values from the multi select options list?

I have added a button in my form and I need to find out the selected options when I click the button.

I tried with call back that seems to respond for every click. I need to get the selected values once even if the user did not explicitly selected an option (need to get the default values).


$('#MultipleOptions').multiSelect( null, function(el) {
alert("Option Clicked: " +el.val());
});

Thanks in advance for your help.

Cynthi on Oct 31st, 2008

Another nice script! You're doing some great stuff over here!

Webdesign Meppel on Nov 3rd, 2008

Hi, I have a e-trade project.

I use this script ? This free ?

Thanks.

samet on Nov 5th, 2008

Hi,

First of all thanks for this greatly useful component.

I have a request for feature:
If one of the options is disabled by default(by doing disabled="disabled") then the checkbox should also render disabled by default and "Select All" should not check it.

Currently it doesn't do this.

Thanks

Rachit on Nov 5th, 2008

@samet: Please refer to the licensing section to answer your question.

Cory S.N. LaViska on Nov 5th, 2008

Thanks, but ı don't just understand .

Because, ı don't good understand english. ( and licensing text very long )

samet on Nov 5th, 2008

I'd like to see an answer to Cynthia's question, because I too am baffled. How do you get the selected values out of the control?

Steve on Nov 5th, 2008

@Cynthi & Steve: see the demo for how to retrieve the selected values. When placed in a form, it will submit the same way as it would if it were just a SELECT element. That said, you can use $.serialize() or simply check the value using document.getElementById.

Cory S.N. LaViska on Nov 5th, 2008

example:

<option value="1">One</option>
<option value="2">Two</option>
<option value="3">There</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
**

I selected One,Three,Five and Four.

Output : /1/Three/5/4

sometimes,

output: /One/3/Five/4


I one by one choosing box , sometimes corrupt output. But I checked "select all" everything normal.

its time output : /1/3/5/4

Cause ? :S

samet on Nov 7th, 2008

Hello,
Thank you for your nice pluggin.
Nevertheless I've notice that if the <select> is in a div with "position:fixed" attribute, the droplist is not displayed.
I've not managed to found a solution ... does a solution exist ?
Thanks
NLA

nla on Nov 12th, 2008

pretty control by works slowly on large amount of data due to the fact the author does not use direct addressing of html elements of the control. This approach increases a cost of a support of the control as well.

JOhn on Dec 8th, 2008

If you use <label for="x">CHB</label><input type="checkbox" id="x" ... /> then the label clicks will trigger the checkbox. I hope it helps.

Caner on Dec 8th, 2008

Good but don't work with any form-styler like jform. Like Nathan, I add input id support.

ben on Dec 10th, 2008

Hi,

I'm using this plugin with worpress, but the effect only works in the home page.
Any ideas ?
Thanks
www.kalyrock.com

ado on Dec 13th, 2008

Nathan's Class and selectExclusive + Id and Pagination, skinnable, would be great to have a good and usable release.

ben on Dec 18th, 2008

I would like to suggest a feature to initialize without checked options, I modify the plugin commenting the line 50 to get this behavior.

'//if( $(this).attr('selected') ) html += ' checked="checked"';'

Good plugin!

Felipe on Dec 24th, 2008

Hi all,

I use it on Asp.net DropDownList control, but found "AutoPostBack" failed.

The same thing happen on javascript onChange() event.

Can anyone help?

By the way, it's really a good plugin.


derek on Dec 30th, 2008

Hi,

Thanks for a great Plugin...
Instead of using checkbox can i make use of textbox if so how do i get sum of values of text box's within a select

Mahesh on Jan 2nd, 2009

Further to the above question, How to evaluate onchange of select

Mahesh Dasari on Jan 5th, 2009

First off all: thanks for this beautifull plugin. It works like a charm in FF but in IE7 i'm experiencing some problems.

I have an empty page with a large multiselect list of items (400+). When i load this page without the plugin it takes about 1,5 second to load the page. With the plugin enabled the page loads in 2 seconds in FF but IE7 takes up to 10 seconds (!!!) to load the page. While loading IE hangs . This is really really annoying and i'm bumping my head over it for a couple of days now . Does anyone got an idea how to fix this?

Marc on Jan 11th, 2009

how to count the selection?
ex:
if (nothing_selected) alert ('please select smth')

misha antsibor on Jan 12th, 2009

solution :

var selected_count = $(".multiSelectOptions input[type=checkbox]:checked").length;

misha antsibor on Jan 12th, 2009

how to show selected after form submition ?

loop %selected_values index=%i
$(".multiSelectOptions input[value=%i]").each(function() {
this.checked = true;
$(this).parent().addClass('checked');
});

end selected_values_loop

misha antsibor on Jan 12th, 2009

@Marc - I don't think you can really expect a plugin of this nature to handle that many items in one list...it would also seem like it would be bad for usability.

You might benefit more from a custom script where you can group similar items and maybe even offer your users a search feature for those 400+ options.

Cory S.N. LaViska on Jan 12th, 2009

I had an issue with it always selecting the first value in the drop down instead of all if it wasn't explicitly set. Here are my changes to get that working:

Line 50: if ($(this).attr('selected') && $(this).attr('defaultSelected')) html += ' checked="checked"';
Line 82: if ($(this).attr('checked')) sa = false;

Matt Elliott on Jan 15th, 2009

Correction to Line 50:if ($(this).attr('defaultSelected')) html += ' checked="checked"';

Matt Elliott on Jan 15th, 2009

How to select the option(s) in javascript?Thanks for any help of anyboby.for example I want to -----elementSelect.options[1].selected=true;

wofei on Jan 17th, 2009

Hey, great control; thanks. I found one bug but I was able to fix it for my case. If a select option had a double quote (") in the value, ASP.NET wasn't picking up on the item being selected.

I edited the JS and where it is building the value of the checkbox, I added:

.replace(/\"/g, '&quot;')

Worked like a charm (for my case anyway).

Jeff Handley on Jan 18th, 2009

How do I show the multiselect box always expanded. Also, onblur event on select box never works, any ideas greatly appreciate

kumar on Jan 20th, 2009

hello,

Great plugin! I added some code to support <optgroup>. It just replaces the <optgroup> label attribute with a <label> tag.

I changed this:

$(select).find('OPTION').each( function() {
if( $(this).val() != '' ) {
html += '<label><input type="checkbox" name="' + $(select).attr('name') + '" value="' + $(this).val() + '"';
if( $(this).attr('selected') ) html += ' checked="checked"';
html += ' />' + $(this).html() + '</label>';
}
});

To this:

$(select).find('OPTION').each( function() {
var optgroup = $(this).parent('OPTGROUP');
if( optgroup && $(this).is(":first-child") ) {
if( optgroup.attr("label") != '') {
html += '<label><strong><i>' + optgroup.attr("label") + '</i></strong></label>';
}
}
if( $(this).val() != '' ) {
html += '<label><input type="checkbox" name="' + $(select).attr('name') + '" value="' + $(this).val() + '"';
if( $(this).attr('selected') ) html += ' checked="checked"';
html += ' />' + $(this).html() + '</label>';
}
});

Seems to work ok.

fehays on Jan 26th, 2009

Oops... my check for optgroup was wrong. should be:
if( optgroup.length > 0 && $(this).is(":first-child") ) {
now it seems to work ok :)

fehays on Jan 26th, 2009

How do we get the selected text instead of selected value?

Seetharaman Srinivasan on Jan 28th, 2009

added the following to the end of the "multiSelectUpdateSelected" function to check the 'select all' if all are selected manually:

if (i == $(this).find("input[type=checkbox]").not('.selectAll').length) {
$(this).parent().parent().find('INPUT:checkbox.selectAll').attr('checked', true).parent().addClass('checked'); ;
}

Matthew on Feb 5th, 2009

Hey
Great work guys!! A realy nice plugin but I am facing a problem with it. I have added a multi select on my form. I open my form and select soem checkboxes. The labels become bold where i have checked and the count increments to n-optoins selected in the title.
Now i press the cancel button and close my form and then reopen it.

The multiselect has no-options selected but the problem is it still shows n-options selected in the title and all the values that i selected are still in bold.

Is this is bug? Is any work around available? Any help would be appreciated

Thanks
Heamnt

Hemant on Feb 9th, 2009

Cory,

I love this, and for the most part so do my users. I sent you a separate message about a problem in MS IE 7, where a long list of options did not get a scroll bar, and was clipped, preventing users from getting to items at the bottom of the list. It worked fine in Firefox, Chrome, and Safari.

Since then I found a temporary workaround. My workaround is a bit ugly, though: I added height: 300px to the
.multiSelectOptions class from your CSS. That means even if their are only 3 choices, a big 300px high box drops down.

(BTW, none of the browsers seems to respect any settings for SIZE="" in the SELECT tag. They all drop about the same amount.)

BogeyBill on Feb 12th, 2009

Please help guys, is there a way to limit the number of selected options (checked items) in the list?

kiki on Feb 13th, 2009

Hey. Very elegant little plugin. It's probably the easiest to use of all the one's I've found.
I used it with an ASP.NET LISTBOX control. It *almost* works like I want it to... But I suspect it's probably me who doesn't know what I am doing.
Basically AutopostBack=true is ignored when I apply the plugin to an ASP.NET control. Is this intentional? Does anyone know a way around it?
Secondly none of the items I selected are marked as selected when I try to retrieve them in the codebehind (C#). Has anyone managed to successfully use it with ASP.NET and retrieve the values on the *SERVER* ?
If so, would you be so kind as to throw a few pointers my way? :-)

timidllama on Feb 15th, 2009

Hi All

I am facing a problem with this plugin. The drop downs fails to collapse when we click anywhere else on the form and in case i have more that 1 multiselects on my form they behave very funny sometimes like clicking on the title for first multiselect it will open the second one as well.

Is there a way to collapse the multiselect when clicked any where else? I am using it on safari

Any help or pointers will be appreciated

Thanks
Hemant

Hemant on Feb 16th, 2009

Nice plugin, hoping it'll work for us. Any chance this could go up on github? I know I'll end up enhancing it to support the "close if you click anywhere else" issue. I'll also be adding hierarchical options (in effect making a checkbox tree that downgrades to a multi-select HTML tag), and I'd love to be able to submit changes back to the project.

Ben Strackany on Feb 17th, 2009

Hi, I want to add this to my form however it looks different to my regular select boxes. I don't think there's a way to style my other select boxes to look like this one as certain elements are controlled by the OS. Do you know of a work around? Many thanks,

Richard Hayes on Feb 18th, 2009

Thanks for the Great plugin.
But i have some problem
1)If the option text is more than the div width the text comes down.
2) if the text in the text box increases then background image is pushed.

Shrikanth Kalluraya on Feb 26th, 2009

Cool! Exactly what i was looking for. If my new website makes me a zillionaire, i'll donate you a billion...
Thanks a lot
Peter

Peter on Feb 26th, 2009

Cory, just wanted to say this is a great plug-in, very slick and worked with very minimal fuss.

I would just second James comment (#23 James on Oct 3rd, 2008) that with the new versions of jQuery, you don't need the dimensions script. Also, I had to do what he suggested regarding changing

var offset = $(this).offset();
to
var offset = $(this).position();

Without this, the menu was displaying in the wrong position relative to the original select element.

But thanks again, great effort!

Jono Ward on Mar 5th, 2009

I have a very simple question: How can I get the select tag object -- I need the value of the select tag's id attribute.

I can't use $(this).parent(). Using a parameter in the function I get closer:

function(el) {
console.log(el.parent().attr("id"));
}

but the parent isn't the select element, and neither is the grandparent. I'd love to solve this. Thanks!

Ann on Mar 11th, 2009

Hi, good job. I was trying to get the list without a form submit like your example. This is my code, sorry but i am new:

$(document).ready(function(){


$('#cmbLugarPago').multiSelect({
selectAll: true,
selectAllText: 'Todos',
noneSelected: 'Seleccione una opción',
oneOrMoreSelected: '% Opcion(es) Seleccionada(s)'
}
);

$('#cmbTributo').multiSelect({
selectAll: true,
selectAllText: 'Todos',
noneSelected: 'Seleccione una opción',
oneOrMoreSelected: '% Opcion(es) Seleccionada(s)'
}
);


$('#btnProcesar').click(function()
{
var sTipoReporte= $('#cmbTipoReporte').val();
if(Validar(sTipoReporte)==1)
{
switch(sTipoReporte)
{
case 'PagoGen': PagoGeneral();break;
case 'PagoDia': PagoDia();break;
case 'PagoCaj': PagoCajero();break;
}
}
else
{
alert('Ingrese la información necesaria para realizar la consulta.');
}
}
);

});

function PagoGeneral()
{
//I want to get here the list of selected items
//i did this
alert($('#cmbLugarPago').serialize().replace(/&/g, '\n'));
}

So, what should i put ????

thanks so much

Erick on Mar 19th, 2009

Hello World!

Good plugin.

When the mouse leave the dropdown, the hover "event" is not unbind, because "hover" is not an event but a helper for the mouseenter and mouseleave events.

Just replace in the source file :

.unbind("hover")

by

.unbind("mouseenter mouseleave")

Peace be upon you.

Mohamed on Mar 23rd, 2009

I had a "clear form" button on my page that cleared the values of the multiselect select list, but since this moves that to a series of checkboxes, it broke. Any suggestions on how to clear all selections within a given select list?

Old code was:

function resetSelect(selectObj) {
for (i=0;i<selectObj.options.length;i++){
selectObj.options[i].selected=false;
}
}

Ioldanach on Apr 7th, 2009

lines 240-248 reference $ as a global and not jQuery. When using .noConflict() this code fails. We replaced those $ references with jQuery references and it works.

// Disappear on hover out
multiSelectCurrent = $(this);
var timer = '';
$(this).next('.multiSelectOptions').hover( function() {
clearTimeout(timer);
}, function() {
timer = setTimeout('jQuery(multiSelectCurrent).multiSelectOptionsHide(); jQuery(multiSelectCurrent).unbind("hover");', 250);
});

John Rice on Apr 8th, 2009

First of all thanks for this great plugin.
I have a small problem using it, my multiselect control is is lower down the bottom, of the page and when it opens the select box goes out of visible page. I dont know whether its a bug or I am doing something wrong.

kapil on Apr 9th, 2009

For limited option selected you can used this

$("#control_1").multiSelect(option, function(el) {
var selected_count =$(".multiSelectOptions input[type=checkbox]:checked").length;

if(selected_count > 3){

el.attr('checked',false);
alert("Vous ne pouvez pas choisir plus de 3 option");

}

});

Cédric on Apr 9th, 2009

aafdsad

afa on Apr 28th, 2009

Thak you guys, I love your plugin, it's really useful and well done :)

Sanbor on May 4th, 2009



I have added few changes in this great control, i warped with another div, and set the new div ID the same ID that the select had, i also fix the bug of hiding the control
when ever the the select section was open but not hover(in this scenerio it's didn't colose up), and finally in the added new div
i put as value all the selected values,
have fun

/*
// jQuery multiSelect
//
// Version 1.0.1 beta
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 06 April 2008
//
// Visit http://abeautifulsite.net/notebook.php?article=62 for more information
//
// Usage: $('#control_id').multiSelect( options, callback )
//
// Options: selectAll - whether or not to display the Select All option; true/false, default = true
// selectAllText - text to display for selecting/unselecting all options simultaneously
// noneSelected - text to display when there are no selected items in the list
// oneOrMoreSelected - text to display when there are one or more selected items in the list
// (note: you can use % as a placeholder for the number of items selected).
// Use * to show a comma separated list of all selected; default = '% selected'
//
// Dependencies: jQuery 1.2.6 or higher (http://jquery.com/)
//
// Change Log:
//
// 1.0.1 - Updated to work with jQuery 1.2.6+ (no longer requires the dimensions plugin)
// - Changed $(this).offset() to $(this).position(), per James' and Jono's suggestions
//
//
// Licensing & Terms of Use
//
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC.
//
*/
if(jQuery) (function($){

$.extend($.fn, {
multiSelect: function(o, callback) {
// Default options
if( !o ) var o = {};
if( o.selectAll == undefined ) o.selectAll = true;
if( o.selectAllText == undefined ) o.selectAllText = "Select All";
if( o.noneSelected == undefined ) o.noneSelected = 'Select options';
if( o.oneOrMoreSelected == undefined ) o.oneOrMoreSelected = '% selected';

// Initialize each multiSelect
$(this).each( function() {
var select = $(this);
var html = '<input type="text" readonly="readonly" class="multiSelect" value="" style="cursor: default;" />';
html += '<div class="multiSelectOptions" style="position: absolute; z-index: 99999; display: none;">';
if( o.selectAll ) html += '<label class="selectAll"><input type="checkbox" class="selectAll" />' + o.selectAllText + '</label>';
$(select).find('OPTION').each( function() {
if( $(this).val() != '' ) {
html += '<label><input type="checkbox" name="' + $(select).attr('name') + '" value="' + $(this).val() + '"';
if( $(this).attr('selected') ) html += ' checked="checked"';
html += ' />' + $(this).html() + '</label>';
}
});
html += '</div>';



$(select).wrap("<div id="+$(select).attr('id')+" ></div>");

$(select).after(html);

// Events
$(select).next('.multiSelect').mouseover( function() {
$(this).addClass('hover');
}).mouseout( function() {
$(this).removeClass('hover');
}).click( function() {
// Show/hide on click
if( $(this).hasClass('active') ) {
$(this).multiSelectOptionsHide();
} else {
$(this).multiSelectOptionsShow();
}
return false;
}).focus( function() {
// So it can be styled with CSS
$(this).addClass('focus');
}).blur( function() {
// So it can be styled with CSS
$(this).removeClass('focus');
});

// Determine if Select All should be checked initially
if( o.selectAll ) {
var sa = true;
$(select).next('.multiSelect').next('.multiSelectOptions').find('INPUT:checkbox').not('.selectAll').each( function() {
if( !$(this).attr('checked') ) sa = false;
});
if( sa ) $(select).next('.multiSelect').next('.multiSelectOptions').find('INPUT.selectAll').attr('checked', true).parent().addClass('checked');
}

// Handle Select All
$(select).next('.multiSelect').next('.multiSelectOptions').find('INPUT.selectAll').click( function() {
if( $(this).attr('checked') == true ) $(this).parent().parent().find('INPUT:checkbox').attr('checked', true).parent().addClass('checked'); else $(this).parent().parent().find('INPUT:checkbox').attr('checked', false).parent().removeClass('checked');
});

// Handle checkboxes
$(select).next('.multiSelect').next('.multiSelectOptions').find('INPUT:checkbox').click( function() {
$(this).parent().parent().multiSelectUpdateSelected(o);
$(this).parent().parent().find('LABEL').removeClass('checked').find('INPUT:checked').parent().addClass('checked');
$(this).parent().parent().prev('.multiSelect').focus();
if( !$(this).attr('checked') ) $(this).parent().parent().find('INPUT:checkbox.selectAll').attr('checked', false).parent().removeClass('checked');
if( callback ) callback($(this));
});

// Initial display
$(select).next('.multiSelect').next('.multiSelectOptions').each( function() {
$(this).multiSelectUpdateSelected(o);
$(this).find('INPUT:checked').parent().addClass('checked');
});

// Handle hovers
$(select).next('.multiSelect').next('.multiSelectOptions').find('LABEL').mouseover( function() {
$(this).parent().find('LABEL').removeClass('hover');
$(this).addClass('hover');
}).mouseout( function() {
$(this).parent().find('LABEL').removeClass('hover');
});

// Keyboard
$(select).next('.multiSelect').keydown( function(e) {
// Is dropdown visible?
if( $(this).next('.multiSelectOptions').is(':visible') ) {
// Dropdown is visible
// Tab
if( e.keyCode == 9 ) {
$(this).addClass('focus').trigger('click'); // esc, left, right - hide
$(this).focus().next(':input').focus();
return true;
}

// ESC, Left, Right
if( e.keyCode == 27 || e.keyCode == 37 || e.keyCode == 39 ) {
// Hide dropdown
$(this).addClass('focus').trigger('click');
}
// Down
if( e.keyCode == 40 ) {
if( !$(this).next('.multiSelectOptions').find('LABEL').hasClass('hover') ) {
// Default to first item
$(this).next('.multiSelectOptions').find('LABEL:first').addClass('hover');
} else {
// Move down, cycle to top if on bottom
$(this).next('.multiSelectOptions').find('LABEL.hover').removeClass('hover').next('LABEL').addClass('hover');
if( !$(this).next('.multiSelectOptions').find('LABEL').hasClass('hover') ) {
$(this).next('.multiSelectOptions').find('LABEL:first').addClass('hover');
}
}
return false;
}
// Up
if( e.keyCode == 38 ) {
if( !$(this).next('.multiSelectOptions').find('LABEL').hasClass('hover') ) {
// Default to first item
$(this).next('.multiSelectOptions').find('LABEL:first').addClass('hover');
} else {
// Move up, cycle to bottom if on top
$(this).next('.multiSelectOptions').find('LABEL.hover').removeClass('hover').prev('LABEL').addClass('hover');
if( !$(this).next('.multiSelectOptions').find('LABEL').hasClass('hover') ) {
$(this).next('.multiSelectOptions').find('LABEL:last').addClass('hover');
}
}
return false;
}
// Enter, Space
if( e.keyCode == 13 || e.keyCode == 32 ) {
// Select All
if( $(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').hasClass('selectAll') ) {
if( $(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').attr('checked') ) {
// Uncheck all
$(this).next('.multiSelectOptions').find('INPUT:checkbox').attr('checked', false).parent().removeClass('checked');
} else {
// Check all
$(this).next('.multiSelectOptions').find('INPUT:checkbox').attr('checked', true).parent().addClass('checked');
}
$(this).next('.multiSelectOptions').multiSelectUpdateSelected(o);
if( callback ) callback($(this));
return false;
}
// Other checkboxes
if( $(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').attr('checked') ) {
// Uncheck
$(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').attr('checked', false);
$(this).next('.multiSelectOptions').multiSelectUpdateSelected(o);
$(this).next('.multiSelectOptions').find('LABEL').removeClass('checked').find('INPUT:checked').parent().addClass('checked');
// Select all status can't be checked at this point
$(this).next('.multiSelectOptions').find('INPUT:checkbox.selectAll').attr('checked', false).parent().removeClass('checked');
if( callback ) callback($(this));
} else {
// Check
$(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').attr('checked', true);
$(this).next('.multiSelectOptions').multiSelectUpdateSelected(o);
$(this).next('.multiSelectOptions').find('LABEL').removeClass('checked').find('INPUT:checked').parent().addClass('checked');
if( callback ) callback($(this));
}
}
return false;
} else {
// Dropdown is not visible
if( e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 13 || e.keyCode == 32 ) { // down, enter, space - show
// Show dropdown
$(this).removeClass('focus').trigger('click');
$(this).next('.multiSelectOptions').find('LABEL:first').addClass('hover');
return false;
}
// Tab key
if( e.keyCode == 9 ) {
// Shift focus to next INPUT element on page
$(this).focus().next(':input').focus();
return true;
}
}
// Prevent enter key from submitting form
if( e.keyCode == 13 ) return false;
});

// Eliminate the original form element
$(select).remove();
});

},

// Hide the dropdown
multiSelectOptionsHide: function() {
$(this).removeClass('active').next('.multiSelectOptions').hide();
},

// Show the dropdown
multiSelectOptionsShow: function() {
// Hide any open option boxes
$('.multiSelect').multiSelectOptionsHide();
$(this).next('.multiSelectOptions').find('LABEL').removeClass('hover');
$(this).addClass('active').next('.multiSelectOptions').show();

// Position it
var offset = $(this).position();
$(this).next('.multiSelectOptions').css({ top: offset.top + $(this).outerHeight() + 'px' });
$(this).next('.multiSelectOptions').css({ left: offset.left + 'px' });

// Disappear on hover out
multiSelectCurrent = $(this);
var timer = '';
$(this).next('.multiSelectOptions').parent().hover( function() {
clearTimeout(timer);
}, function() {
timer = setTimeout('$(multiSelectCurrent).multiSelectOptionsHide(); $(multiSelectCurrent).unbind("hover");', 250);
});

},

// Update the textbox with the total number of selected items
multiSelectUpdateSelected: function(o) {
var i = 0, s = '',val='';
$(this).find('INPUT:checkbox:checked').not('.selectAll').each( function() {
i++;
})
if( i == 0 ) {
$(this).prev('INPUT.multiSelect').val( o.noneSelected );
} else {

var display = '';
$(this).find('INPUT:checkbox:checked').each( function() {
if( $(this).parent().text() != o.selectAllText )
{
display = display + $(this).parent().text() + ', ';
val = val+ $(this).val()+ ',';
}
});
display = display.substr(0, display.length - 2);
val = val.substr(0, val.length - 1);
$(this).parent().val(val);
if( o.oneOrMoreSelected == '*' ) {
$(this).prev('INPUT.multiSelect').val( display );
}
else {
$(this).prev('INPUT.multiSelect').val( o.oneOrMoreSelected.replace('%', i) );
}
}
}


});

})(jQuery);

zamir dan on May 4th, 2009

Hi all,

I am looking to populate my multi-select based upon a normal HTML select box's content. This means that I would like to use Javascript to add options to the multiselect manually. Does anybody know how to do this, i.e. how to reference a multi-select's options and their corresponding values?

Thanks

Jon B on May 7th, 2009

Hi all,

And first, thanx for this work, it rocks ;)

I want to populate the select with ajax.

<code>

$.getJSON("ajax/get_select.php",
function(j){
var options='';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("#control_1").html(options);
});

$("#control_1").multiSelect();

</code>

in the html page :
<code>
<select id="control_1" name="control_1[]" multiple="multiple"></select>
</code>

But in the "select", i can see only the "select all" item.
I must add that when i remove $("#control_1").multiSelect(); the select is correctly populated (without the checkbox of course)

So, I guess it comes from the plugin but in wich way ? have you got any clue ?

regards,

f.

fabrice.regnier on May 7th, 2009

i answer to myself:

instead of using

$("#control_1").html(options); then
$("#control_1").multiSelect(); ouside the getJSON

I use, in the getJSON:
$("#control_1").html(options).multiSelect();

and all works ok.

f.

fabrice.regnier on May 7th, 2009

Hi all,
how to add a vertical scroll bar control function when pageup & pagedown keyboard event?

Matt on May 11th, 2009

http://www.grasvezel.nl/Blog/view/195/jQuery_multiselect_Patch.html a small patch to show a special text whe all is selected

Utopia on May 15th, 2009

thanks for this plugin, but, can i use an efect OnClick with this plugin?

salud on May 15th, 2009

For those who have more space left ;-), and need the selected items to be sortable, here's an alternative.

http://quasipartikel.at/multiselect

Michael Aufreiter on May 18th, 2009

Hi, I have a strange problem. In one of my php pages the select is working superb, but in the other pages it's not. There are no values in the POST. The pages are almost identical. Any ideas for solving the problem?

Kristian Chakarov on May 25th, 2009

When the "Select All" option provided and is selected, can I get the string "All" shown instead of % selected or the comma separated list of values?

Mike on May 26th, 2009

Hi!

Just made me a quick function to get all selected values in a given select.

function getMSvalues(selectId) {
myArray = [];
$(".multiSelectOptions input[name="+selectId+"][type=checkbox]:checked").log("Checked Regions selector:").each( function( intIndex ){
myArray.push( $(this).val() );
});
return myArray;
}

Usage: myArray = getMSselected('your_select_id');
It will return an array fill with each selected option value.

Guzmán Brasó on May 26th, 2009

Sorry! Left some debugging in the code above.
Below the correct version:

function getMSvalues(selectName) {
myArray = [];
$(".multiSelectOptions input[name="+selectName+"][type=checkbox]:checked").each( function( intIndex ){
myArray.push( $(this).val() );
});
return myArray;
}

Guzmán Brasó on May 26th, 2009

@Ioldanach

I was needing such a thing myself for the project I'm working at... after spending some time taking a peep at the code, I came up with some sort of solution... it's not the best one, I know, and if it is ever to make it into some official version of this multiSelect plugin, my code would need some sort of refactoring... but works for me so far and I can't spend much more time on it...

So here it is a "clear" function for this multiSelect plugin: you need to pass the text to show when cleared though, it won't take the one specified at creation time:

clearMultiSelect: function (text) {
$(this).each(function (i) {
if($(this).attr('checked'))
$(this).parent().parent().find('INPUT:checkbox').attr('checked', false).parent().removeClass('checked');
}).parent().parent().prev('INPUT.multiSelect').val(text);
}

You can paste these lines of code at the end of all the other functions at the jquery.multiSelect.js. Then, you can call this method in the standard jQuery way:

$("#elementID").clearMultiSelect("please select option(s)");

Hope this helps!


FrogDr on May 27th, 2009

Hi,

I am a great fan of the Multiselect Tool.
I noticed this bug recently. In my page, if the options are more than 7, on the drop list, only the 1st seven are rendered. Is there are workaround or a patch to fix this?

Thanks,
Abhisheak

Abhisheak on May 27th, 2009

Hi,

Great script! n its really great that you find the time to update it. Thank a mill.

I have a problem with the browser pausing for too long while leaving a page that runs this script. In FF it says something like 'a script is running for too long : Jquery'. It works fine if i don't call the multiselect function at all on the main page running the script.

Is there a way to unbind the the multiselect function that is applied across all the select boxes on a click of a link or on page unload? Please let me know .. ive tried everything from die() to event listeners, although i'm a novice at javascript.

Alston on Jun 4th, 2009

GREAT plug-in! I am using it across the Advertising Manager Wordpress plug-in. One thing that I would love to see is the ability to type a few letters in to the combo box, and the list results filter (e.g. if you have a dropdown of states, you can type 'New' and the 50 results filter into New York, New Jersey, New Hampshire, etc.)

Could this be baked in? From the number of comments here, there is no shortage of things to do, but this feature would mean nirvana to me :)

Cheers...

Scott on Jun 9th, 2009

Great plugin, but I can't find a simple way to dynamically select options. Once i have the multiselect set-up, how can I toggle some of the checkboxes by code? I couldn't find a simple way to retrieve the list of selected values either.

axel on Jun 16th, 2009

This is a fantastic plugin - I've made minor customisations to allow only single selections and to display the value current selection in INPUT.multiselect

In the section:
// Update the textbox with the total number of selected items

I replaced:
$(this).prev('INPUT.multiSelect').val( o.oneOrMoreSelected.replace('%', i) );

with:
if (o.selectExclusive){ $(this).prev("INPUT.multiSelect").val( $(this).find("INPUT:checkbox:checked").val() );
} else {
$(this).prev('INPUT.multiSelect').val( o.oneOrMoreSelected.replace('%', i) );
}

This works as desired, setting INPUT.multiselect to the selected value BUT only when selecting an option higher in the list (earlier in the html).

When selecting an option lower in the list(later in the html) it shows the previous selected value.

Any ideas why this would occur?

Paul on Jun 16th, 2009

SELF FIX:

Ammended my changes to section:
// Handle checkboxes

Moved following to first line within function instead of last line:
if (o.selectExclusive){ $(this).parents('.multiSelectOptions').find('input:checked[value!=' + $(this).attr('value') + ']').attr('checked', false).parent().removeClass('checked');
}

Now the style of my multi select and single select boxes match!

Paul on Jun 16th, 2009

Great plug-in!

But dynamically added items (by javascript) will not show up in the dropdown box. Is there a way to reload/refresh the dropdown box?

Calling $("#control_id").multiSelect(); after adding the new items doesn't work.

thanks

pegen on Jun 17th, 2009

Paul, please, could you explain a bit more where to put the modifications to be able to match both styles?

fmonera on Jun 20th, 2009

Paul, you can avoid the user to unselect an option if you add this:
if(!$(this).attr('checked') ) $(this).attr('checked', true).parent().addClass('checked');

below your line (but inside the function):
$(this).parents('.multiSelectOptions').find('input:checked[value!=' + $(this).attr('value') + ']').attr('checked', false).parent().removeClass('checked');

Disclaimer: this is my very first line written in javascript :P , really, so expect a lot of bugs :D

fmonera on Jun 20th, 2009

This plug-in is great so far, but currently I'm having a problem with how it's rendering inside of a div dialog (using jQuery Boxy dialog plug-in). It's rendering very strangely. I have the solution at home, I'll have to check and get more details. Just wondering if this is a know issue or if anyone has a solution.

Andrew Lundgren on Jun 26th, 2009

I had to set the dialog's inner DIV to position:relative, makes sense.

Andrew Lundgren on Jul 1st, 2009

Add a comment

Name*

Email*

Never, ever sold or spammed :)

Homepage

Comment*

Sorry, plain text only :(