Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a selected value in a dropdown list using Mustache.js?

Tags:

Is it possible to do this with Mustache.js?

var data = {"val":"3"},     template = '<select>' +                     '<option value="1">1</option>' +                     '<option value="2">2</option>' +                     '<option value="3">3</option>' +                 '</select>';  var html = Mustache.to_html(template, data);  $(html).appendTo('body'); 
like image 975
nolabel Avatar asked Apr 01 '11 21:04

nolabel


2 Answers

The val attribute doesn't work, because a <select> takes its value from the <option>s which have the selected attribute. I'm not very familar with Mustache, but this should work:

// snip...         var html = Mustache.to_html(template, data); $(html)     .find('option[value=3]').attr('selected', true)     .end().appendTo('body'); 

I think that the template you're using is not idiomatic Mustache — it's too coarse grained; you're not actually templating anything. Something like this might be more Mustache-y:

var template = '<select>{{#options}}' +                    '<option value="{{val}}" {{#sel}}selected{{/sel}}>' +                         '{{txt}}' +                     '</option>' +                 '{{/options}}</select>',      data = {options: [         {val: 1, txt: 'uno'},         {val: 2, txt: 'dos'},         {val: 3, txt: 'tres', sel: true}     ]};  var html = Mustache.to_html(template, data);  $(html).appendTo('body'); 

Demo →

like image 56
Matt Ball Avatar answered Sep 17 '22 14:09

Matt Ball


if you do not want to modify the array or DOM tree afterwards you can use a function:

var selval=3; // select 3 var template = '<select>{{#options}}' +                    '<option value="{{val}}" {{selected}}>{{txt}}</option>' +                 '{{/options}}</select>'; var data={     options: [         {val: 1, txt: 'one'},         {val: 2, txt: 'two'},         {val: 3, txt: 'three'}     ],     selected: function() {          if (this.val==selval) return "selected";          return "";     } };   var html = Mustache.to_html(template, data); 
like image 35
imperator Avatar answered Sep 18 '22 14:09

imperator