3
\$\begingroup\$

I had three multi-select boxes from this page. I want to customize each box so I simply repeat the code three times with different options: Check the fiddle

$(".choose").multiselect({ 
   header: "Choose only One item!",
   multiple: false,
   noneSelectedText: "Select an Option",
   selectedList: 1
});

$(".pick").multiselect({
    header: "Pick Any",
selectedList: 5 
});

$(".filter").multiselect({
    header: "Filter Three",
   selectedList: 3 
});

It's working fine but I'm curious if there's any better way to do that.

\$\endgroup\$
0

2 Answers 2

4
\$\begingroup\$

With only three different items I don't think there's much benefit from iterating through a list and instantiating the multi-selects automatically. Your version IMO is much more legible than a version iterating through an embedded data structure. Although with lots of selects this could change fast.

You could take the approach of specifying the attributes of the selects (header, noneSelectedText etc.) as data attributes on the HTML. Then you could wire up your jQuery multiselect code to read the information from the selects themselves. So your jQuery would only have to specify the type of select to trigger the multiselect call on and you could add as many as you like without having to update your scripts.

So something like this:

<select class="dynamic-multiselect" data-header="Choose only One item!" data-none-selected-text="Select an Option" ...>
    <option ...>
    ...
</select>

<select class="dynamic-multiselect" data-header="Pick Any"  ...>
    <option ...>
    ...
</select>
...

And the Javascript would simply be:

$('.dynamic-multiselect').multiselect();
\$\endgroup\$
3
\$\begingroup\$

Because you have different options for each one, there isn't really an efficient way to combine them into a common selector. And, with only three items, other options aren't really that likely to be more compact. Here's a pure table driven mode that would be more advantageous if you had many more of these:

var multiData = [{ 
    sel: ".choose", 
    options: { header: "Choose only One item!",  multiple: false,
             noneSelectedText: "Select an Option", selectedList: 1 }
 }, { 
    sel: ".pick",
    options: { header: "Pick Any", selectedList: 5 }
 }, { 
     sel: ".filter",
     options: { header: "Filter Three", selectedList: 3 }
 }];

$.each(multiData, function(index, item) {
     $(item.sel).multiselect(item.options);
});

FYI, your jsFiddle doesn't work on Chrome because Chrome won't run scripts linked directly from github (because scripts from gitjub are reported as text/plain).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.