patternjavascriptMinor
Do I need to trim this jQuery code?
Viewed 0 times
thistrimneedjquerycode
Problem
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
It's working fine but I'm curious if there's any better way to do that.
$(".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.
Solution
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 (
So something like this:
And the Javascript would simply be:
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:
...
...
...And the Javascript would simply be:
$('.dynamic-multiselect').multiselect();Code Snippets
<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>
...$('.dynamic-multiselect').multiselect();Context
StackExchange Code Review Q#43584, answer score: 4
Revisions (0)
No revisions yet.