Manu S Manu S - 22 days ago 6
Javascript Question

handlebar select box populate

my HTML code,

I want each user role is selected next to the select box of each user name,

inside the each loop of role i cant able to access the role of parent user node,
is it possible to compare the role id of user node with roles node roleid and when its equal, the option will be selected

<table>
<tr>
<p>peter is employee</p>
<p>john is admin</p>
<p>michel is manager</p>
</tr>
{{#user}}
<tr>
<td>
<input type="text" value="{{name}}">
</td>

<td>
<select>
{{#each ../roles}}
<option value="{{roleid}}">{{value}}</option>
{{/each}}
</select>
</td>
</tr>
{{/user}}




This is may Json

var data = {
"user": [
{ "name": "peter", "role": 1 },
{ "name": "john", "role": 2 },
{ "name": "michel", "role": 3 }
],
"roles": [
{ "roleid": 1, "value":"manager"},
{ "roleid": 2, "value":"employee"},
{ "roleid": 3, "value":"admin"}
]
};


fiddle url https://jsfiddle.net/Manu_S/egbwbfav/2/

thanks

Answer

You can access the parent node values and compare in your select box.

Please follow the Jsfiddle working that

https://jsfiddle.net/gsubbarao/nz0bc0pq/

<script id="t" type="text/x-handlebars">
<table>
<tr>
    <p>peter is employee</p>

  <p>john is admin</p>
  <p>michel is manager</p>
</tr>
<tr>
<td>&nbsp;</td><td></td><td></td>
</tr>
{{#user}}
<tr>
    <td>
        <input type="text" value="{{name}}">
    </td>

    <td>
        <select>
            {{#each ../roles}}
            <option value="{{roleid}}"
            {{#ifCond  ../role roleid}}
            selected
            {{/ifCond}}
            >
            {{value}}
            </option>

            {{/each}}
        </select>
    </td>
</tr>
{{/user}}

</script>

    var data = {
    "user": [
        { "name": "peter", "role": 2 },
        { "name": "john", "role": 3 },
        { "name": "michel", "role": 1 }
    ],
    "roles": [
        { "roleid": 1, "value":"manager"},
        { "roleid": 2, "value":"employee"},
        { "roleid": 3, "value":"admin"}
    ]
};
Handlebars.registerHelper('ifCond', function(v1, v2, options) {
  if(v1 === v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});
var t = Handlebars.compile($('#t').html());
$('body').append(t(data));