Set the selected item in a select list based on template value

后端 未结 5 1762
生来不讨喜
生来不讨喜 2020-12-14 21:23

How can you correctly pre-populate a select control with the current value from the template?

I have a simple form to edit a record where the values for the selected

5条回答
  •  悲&欢浪女
    2020-12-14 21:54

    I had almost an identical problem, but values I was passing were numbers and I believe I have a cleaner solution for that specific case, that is without depending on Handlebars magic.

    In the template:

    
    

    you basically pass the number of the attribute you want selected with _val. This is useful only in a case where each option has a consecutive numerical value. Also note, if you name this attribute 'value', it will get overwritten/ignored by the default, which selects first option.

    Now in the .rendered callback in your JS file:

    Template.templateName.rendered = () ->
        var btn_style = $('#button-style').attr('_val')
        $('#button-style option:nth-child(' + btn_style + ')').attr('selected', 'selected')
    

    This simply selects the 'nth' option in this select field which corresponds to the value we want.

提交回复
热议问题