I have a select box that gets populated through a Backbone Collection:
class Prog.Views.History extends Backbone.View
template: JST['backbone/templates/shapes/history']
tagName: "option"
initialize: ->
@model.bind('change:formatted', @render, this);
render: ->
$(@el).html(@template(history: @model))
this
backbone/templates/shapes/history
<option value="<%=history.get('origin')%>"><%=history.get('origin')%></option>
This works great, all the correct data is presented in the select box, but what I would like is for the first option to be “please select” i.e. a placeholder… I thought about injecting a record called “placeholder” into the collection but it seems like a round about way.
This is how I call it:
appdenDropdown: (history) ->
console.log("append trigger")
view = new Prog.Views.History(model: history)
$('select#history').append(view.render().el)
How can I default this?
First thing I don’t think this implementation is gona work properly, I think the result of the render will be something like:
Attention to the double option.
A proper solution could be this:
Not need of template here.
About the inclusion of the “please select” option.
Include the “please select” option element hardcoded directly in your HTML into the select element.
Then not use
this.$el.html()to populate the select butthis.$el.append(), this will respect the actual default option and it will add the dynamic elements after it.Updated
For example if your select element looks like this:
Just make it looks like this:
As you are using
appendto add the dynamic option elements the placeholder option element will remain.