Search code examples
ruby-on-railshtmlbackbone.jseco

Preload selected options for select


I am using a lot of things (Rails, Backbone.JS, HTML) and I don't know how to load a selected value for a select. I am in a "edit" form and I want to load the info from the server (Rails API) and load the selected option in my form. In rails we have a helper for the select tag but I am using jst.eco files and I don't know how to load the data from the server.


Solution

  • Here is 'a' way. Define a template:

    <script type="text/template" id="category_options_template">
        <select id="CategoryId" name="CategoryId">
            <% _(categories).each(function(c) { %>
                <% if (c.get('IsSelected') == "selected") { %>
                    <option value="<%= c.get('CategoryId') %>" selected="selected"><%- c.get('CategoryName') %></option>
            <% } %>
                <% if (c.get('IsSelected') == "") { %>
                    <option value="<%- c.get('CategoryId') %>" id="<%- c.get('CategoryName') %>"><%- c.get('CategoryName') %></option>
            <% } %>
            <% }); %>
        </select>
    </script>
    

    Fetch your items that are supposed to end up in the drop down box and store them in an array. Example:

    var categories = new Array();
    function fetch_categories() {
         $.ajax({
                url: '/GetCategories',
                dataType: "json",
                success: function (data) {
                    for (i = 0; i < data.length ; i++) {
                        categories[i] = new category_model({
                            CategoryId: data[i].CategoryId,
                            CategoryName: data[i].CategoryName,
                        });
                    }
                },
                error: function (data) {
                    console.log('Error');
                }
            });
        }
    
    var category_model;
    function setup_category_model() {
            product_category_model = Backbone.Model.extend({
                idAttribute: 'CategoryId',
                defaults: {
                    CategoryId: null,
                    CategoryName: null,
                    IsSelected: "",
                },
                urlRoot: '/Categories',
            });
        }
    

    In the render function of view with a model passed in during init:

    var x = this.model.get('CategoryId');
    for (i = 0; i < categories.length; i++) {
        categories[i].set('IsSelected', "");
    
        if (x && x == categories[i].get('CategoryId')) {
            categories[i].set('IsSelected', "selected");
        }
    }
    var categories_view = _.template($("#category_options_template").html(), {
        categories: categories,
        labelValue: 'Categories'
    });