Search code examples
jqueryjsonhandlebars.js

Jquery / Handlebars.js populate select field from json array


I need, based on the json array "option" to populate an select field

My Script look like this:

var option =  [
    {"mod":"A","values":
        {"Field":"A","Value":"101"}
    },
    {"mod":"B","values:
        {"Field":"B","Value":"102"}},
    {"mod":"C","values"
        {"Field":"C","Value":"99"}
    },
    {"mod":"D","values":    
        {"Field":"D","Value":"96"}
    }];


var theTemplateScript = $('#shoe-template').html(); 
var theTemplate = Handlebars.compile(theTemplateScript); 
$('.shoesNav').append(theTemplate(option));

and my html is as follow:

<script id="shoe-template" type="x-handlebars-template">
    {{#each option}}
        <option value="{{values.Value}}">
           {{values.Field}}
        </option>
    {{/each}}

</script>
<select class="shoesNav">        
</select>

I don't have any console error, however the field is not being populated, what am I missing ?

JSFiddle HERE


Solution

  • You need to namespace the data object with the key in the {{#each option}} loop, which in this case is option. Here's a working implementation:

    var namespace = 'option';
    var data = {};
    
    data[namespace] = [{
        "mod": "A",
        "values": {
            "Field": "A",
            "Value": "101"
        }
    }, {
        "mod": "B",
        "values": {
            "Field": "B",
            "Value": "102"
        }
    }, {
        "mod": "C",
        "values": {
            "Field": "C",
            "Value": "99"
        }
    }, {
        "mod": "D",
        "values": {
            "Field": "D",
            "Value": "96"
        }
    }];
    
    var theTemplateScript = $('#shoe-template').html();
    var theTemplate = Handlebars.compile(theTemplateScript);
    $('.shoesNav').append(theTemplate(data));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
    <script src="https://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
    <script id="shoe-template" type="x-handlebars-template">
        {{#each option}}
        <option value="{{values.Value}}">
            {{values.Field}}
        </option>
        {{/each}}
    </script>
    <select class="shoesNav">
    </select>
    I also updated your fiddle: http://jsfiddle.net/cu7n6j95/3/

    I hope that helps.