Search code examples
javascriptbackbone.js

How to mark <option> as selected in template with Backbone


I have some code which inserts data into a template:

<script type="text/template" id="yes-or-no-tpl">
  <select>
    <option value=""></option>
    <option value="y" <%= "y" == value ? "selected" : "" }}>Yes</option>
    <option value="n" <%= "n" == value ? "selected" : "" }}>No</option>
  </select>
</script>

So far I have only found questions regarding how to react to a user selecting an option. I want to mark the option as selected before the user sees the field.

This code works, but I figured there must be a more elegant solution. Does Backbone have something built in to do this?

I checked out backbone-forms, but I did not find any way to specify a pre-selected option.


Solution

  • You can always do it programmatically with jQuery after rendering the template. There's not much saving here for a yes-or-no template, but if you had 50 options in the select, it would reduce the verbosity a lot.

    var value = 'n'
      , tmpFn = _.template($('#yes-or-no-tpl').html())
      , $el = $('#result');
      
    $el.html(tmpFn());
    $el.find('option[value="' + value + '"]').attr('selected', 'selected');
    
    // view.$el.html(tmpFn());
    // view.$('option[value="' + value + '"]').attr('selected', 'selected');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
    <script type="text/template" id="yes-or-no-tpl">
      <select>
        <option value=""></option>
        <option value="y">Yes</option>
        <option value="n">No</option>
      </select>
    </script>
    <div id="result"/>

    And in relation to built in options, Backbone doesn't include any data binding. You could look into an add-on library like Epoxy.js, but watch out for poorly maintained tools, might be more hassle in the long run.