views:

467

answers:

3

Anyone ever use the toChecklist jQuery plugin? It basically turns a multi-select box into a list of checkboxes. Makes it easier for users to understand that they can choose more than one item - excellent plugin.

However, I'm trying to make sure that users on my site pick at least 1 item in the list. ToChecklist has the capability of limiting the selection to a max value, but not minimum.

I'm already using the jQuery validate plugin to validate the whole form, any ideas to get it to work against a multi-select box (which would then hopefully just work with toChecklist)?

Thanks in advance!

+1  A: 

You can use the length property to see how many elements there are in the array. (Every jQuery object is also an array)

$(anything).length

http://api.jquery.com/length/

if ($("#mychecklist").length > 0)
{
  // valid - has 1 or more.
}
else
{
  // invalid - has 0 items.
}
Hogan
+1  A: 

The .toCheckList() still leaves the original <select> options intact, just hidden. This gives you the selected count using the :selected selector:

If you called $("#myList").toCheckList(), the code to get selected count would be:

$("#myList :selected").length

Used like:

if($("#myList :selected").length > 0)
  alert("Some options are selected!");
else
  alert("Oh snap! better pick something");
Nick Craver
Thank you, so do you think I could use the jQuery validate plugin to do this? I believe I tried required(), but maybe minlength() would work? Not at my dev PC at the moment, can't test.
Chad
@Chad - You can use required and minlength for this, `required: true;` should be equivalent to `minlegth: 1`, but you can do a combo: `required: true, minlength: 3` //Pick at least 3, etc.
Nick Craver
Thanks, for some reason it didn't work when I tried some time ago... a couple of issues have come up recently that got me interested in it again. I'll give this a try.
Chad
hmm, when I try to validate the field name categories[] (it is posted to the server as an array), toChecklist no longer changes the multi-select into a checklist. hmm...
Chad
nm, got it... just a heads up, you have to surround element names with quotes if it is an array type. (i.e. "categories[]" instead of just categories[]
Chad
@Chad - Thanks! That's good to know, I have some selects to validate coming up as well.
Nick Craver
@Nick np man, gl with your next project.
Chad
A: 

Do you have any idea how to validate ui.multiselect http://quasipartikel.at/multiselect/ by using jquery validation plugin?

Iggy