I have a dust.js template file to which I pass 2 arrays:
How can I select the options in the dropdown in dust.js?
Here is an example:
The data I send to the template
var selectOptions = [1,2,3,4,5,6,7,8,9,10,11,12,13];
var selectedValues = [3,7,9];
The template
<select multiple>
{#selectOptions}
<option>{.}</option>
{/selectOptions}
</select>
How can I use the {selectedValues} to select those options?
Thanks in advance for your help.
Add in another loop to go over your selected options
<select multiple>
{#selectOptions}
<option
{#selectedValues val=.}
{@eq key="{val}" value="{.}"}selected="true"{/eq}
{/selectedValues}
>{.}</option>
{/selectOptions}
</select>
Note that I'm using the Dust Helpers from Linkedin to provide the equality comparison.
Another solution that would make it cleaner for your dust.js template would be to combine both list into a new list of objects.
So using your previous data example :
var selectOptions = [1,2,3,4,5,6,7,8,9,10,11,12,13];
var selectedValues = [3,7,9];
var options = [];
for(var i=0;i<selectOptions.length;i++){
var item = selectOptions[i];
// Option object containing selected value + selected info
var option = { value : item, selected : selectedValues.indexOf(item) > -1 };
options.push(option);
}
Your dust.js template will now look like this :
<select multiple>
{#options}
<option {?selected}selected="true"{/selected}>{value}</option>
{/options}
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With