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

后端 未结 4 1746
南旧
南旧 2020-12-30 01:06

Is it possible to do this with Mustache.js?

var data = {\"val\":\"3\"},
    template = \' takes its value from the 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 = '',

    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 →

提交回复
热议问题