Search code examples
javascriptjqueryhtmlbackbone.js

setting <option> for <select> element


I am accepting a value through database. It is a select box with two options offline and online.

the problem is that this code doesn't work:

<select value="<%=app.selectedValue%>"> 
 <option value="offline">Offline</option>
 <option value="online">Online</option>
</select>

the value attribute of select is to be obtained from database. I use underscore's templating engine for the same.

I receive the correct value from the database but its not setting it on the select element. Can anyone help me how I can get the value from database and then dynamically set the value to the select element so the proper option is selected?

PS: I know about the selected="selected" attribute. The question is how i can use it dynamically.

PPS: Using this in an MVC structure using Backbone Marionette JS frameworks. So solutions with respect to that will be much appreciated.


Solution

  • Another option is to take that logic out of your template and handle it within your Backbone view's render method (or Marionette's onRender event), e.g.:

    // ... within the render() method
    $("#out").html(this.template());  // render the template
    $("#out").children("select").val(this.options.app.selectedValue);  // select option based on value
    

    Sample code: http://codepen.io/anon/pen/vOwMPN?editors=101