Alex
Alex

Reputation: 1642

How do we populate a dropdown list's element from a variable in a collection in Meteor?

I am actually trying to do 2 things here:

With 2 dropdown lists,
a) the first would populate with the products, while
b) the second would populate with the colors according to the first dropdown selected.

I starts off insert a document into the collection as below:

ProductList.insert ({ product: "apple", color: "\"red\",\"green\""});  
ProductList.insert ({ product: "banana", color: "\"yellow\",\"green\""});

And this is what I have so far:

Main.html

<template name="prodlist">
<select id="category-select">
        <option disabled="disabled" selected="selected">Please Select</option> 
        {{#each prodlist}}
            <option value="{{this}}">{{this}}</option>
        {{/each}}
    </select>
</template>

<template name="colorlist">
<select id="category-select">
        <option disabled="disabled" selected="selected">Please Select</option> 
        {{#each colorlist}}
            <option value="{{this}}">{{this}}</option>
        {{/each}}
    </select>
</template>  

Main.js

Template.prodlist.helpers({
    prodlist: function(){
        return ProductList.find().map(function(doc) {
            return doc.product
        })
    }
});  

Template.colorlist.helpers({
colorlist: function(){
    return ProductList.find().map(function(doc) {
        return doc.color.split(",")  //<-- edited with MrE's answer
    })

The reason I insert color: "\"red\",\"green\"" is trying to simulate when you populate the dropdown as hardcode: return ["red", "green"], but it return as one element with the string "red","green". Is there a better approach? Also I don't know if there are packages exists that handle dropdown. Thanks in advance.

Upvotes: 0

Views: 48

Answers (1)

MrE
MrE

Reputation: 20768

why do you try to code a string into an array instead of using an array? I'm not sure what that gets you.

If you 'really' want to use a string, you need to parse it ( with doc.color.split(",") ) into an array instead of doing [doc.color]

Upvotes: 1

Related Questions