根据模板值在选择列表中设置所选项目 [英] Set the selected item in a select list based on template value
问题描述
如何使用模板中的当前值正确地预填充选择控件?
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 record are pre-populated when the form is shown. A bit like this:
<input type="text" id="project_name_edit" value="{{selected_name}}">
但是在我使用选择控件的地方,我需要能够交互模板值并有条件地为正确的选项设置 selected='selected'
属性.
But where I am using a select control I need to be able to interogate the template value and conditionally set the selected='selected'
property for the correct option.
<select id="project_status_edit" value="{{selected_status}}">
<option>GOOD</option>
<option>BAD</option>
<option>UGLY</option>
</select>
handlesbars.js 提供了 #IF 帮助程序,但这只会给出真值或假值.
handlesbars.js offers the #IF helper but this only gives truthy or falsy.
我可能会以各种方式破解它,但这似乎是一种有标准解决方案的场景.
I could probably hack this in various way but this seems like a scenario where there would be a standard solution.
推荐答案
您可以使用助手:
Handlebars.registerHelper('selected', function(foo, bar) {
return foo == bar ? ' selected' : '';
});
然后你可以用它来调用:
Which you can then call with:
<select id="project_status_edit">
<option{{selected foo "GOOD"}}>GOOD</option>
<option{{selected foo "BAD"}}>BAD</option>
<option{{selected foo "UGLY"}}>UGLY</option>
</select>
使用:
{"foo":"UGLY"}
在这里试试:
虽然它似乎没有让我保存它.:(
Although it doesn't appear to let me save it. :(
这篇关于根据模板值在选择列表中设置所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!