1

The problem statement over here is that I have a select list which is being populated by handlebar with the help of JSON data from server as shown in data_option variable and then there is other response from server store in data variable which is the actual data to be set for select list. As I have already specify the value while compiling data but still it doesn't selects the value and when I use Jquery to retrieve it throws empty.

<div class="make">
    <script type="text/x-handlears-template" id="make">
        <select class="options" value="{{id}}">
            <option value="">--</option>
        </select>
    </script>
</div>

<script type="text/x-handlears-template" id="options">
    {{#each option}}
        <option value="{{id}}">{{name}}</option>
    {{/each}}
</script>
<script type="text/javascript">
var data = {"id": 3};
var data_options = {
    "option":[
        {
            "id": 1,
            "name": "John Doe"
        },
        {
            "id": 2,
            "name": "James Don"
        },
        {
            "id": 3,
            "name": "John Don"
        },
        {
            "id": 4,
            "name": "James Doe"
        }
    ]
}
var source = $('#make').html();
var template = Handlebars.compile(source);
$('.make').append(template(data));
var source2 = $('#options').html();
var template2 = Handlebars.compile(source2);
$('.options').append(template2(data_options));
</script>
xxCodexx
  • 438
  • 1
  • 3
  • 15
  • Use `.val()` like `$('.make').append(template(data)).val(3);` – Satpal Dec 21 '15 at 09:53
  • This is good but can't we have something that is much more reliable like embedding within the template rather to compile code again – xxCodexx Dec 21 '15 at 10:17

1 Answers1

2

You have to set the selected attribute on the option you wish to select.

You could for example modify your data to set a flag indicating the selection state:

var i, opt;
for (var i=data_options.option.length-1; i>=0; i--) {
    opt = data_options.option[i];
    if (opt.id === data.id) {
        opt.selected = true;
        break;
    }
}

var source2 = $('#options').html();
var template2 = Handlebars.compile(source2);
$('.options').append(template2(data_options));

and use {{#if selected}} ... {{/if}} in your template accordingly

<script type="text/x-handlears-template" id="options">
    {{#each option}}
        {{#if selected}}
            <option value="{{id}}" selected="selected">{{name}}</option>
        {{else}}
            <option value="{{id}}">{{name}}</option>
        {{/if}}
    {{/each}}
</script>

http://jsfiddle.net/nikoshr/p588kp0L/

Community
  • 1
  • 1
nikoshr
  • 32,926
  • 33
  • 91
  • 105