根据模板值将选定项目设置在选择列表中 [英] Set the selected item in a select list based on template value

查看:67
本文介绍了根据模板值将选定项目设置在选择列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何正确地预先填充选择控件与模板中的当前值?我有一个简单的窗体来编辑一个记录,其中的值选定的记录在显示表格时预填充。有点像这样:

 < input type =textid =project_name_editvalue ={{selected_name}} > 

但是在我使用select控件的情况下,我需要能够调用模板值并有条件地设置

 < code> selected ='selected'< code>< ; select id =project_status_editvalue ={{selected_status}}> 
< option> GOOD< / option>
< option> BAD< / option>
< option> UGLY< / option>
< / select>

handlesbars.js提供了#IF助手,但这只会导致真实或错误。



我可能会以各种方式破解这个,但这似乎是一个会有标准解决方案的场景。

  Handlebars.registerHelper('selected',function(foo,bar) ){
return foo == bar?'selected':'';
});

然后您可以拨打电话:

 < select id =project_status_edit> 
< option {{selected fooGOOD}}> GOOD< / option>
< option {{selected fooBAD}}> BAD< / option>
< option {{selected fooUGLY}}> UGLY< / option>
< / select>

使用:

  {foo:UGLY} 

试试这里:



http://tryhandlebarsjs.com/



尽管看起来并没有让我保存它。 :(


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}}">

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 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.

解决方案

You can use a helper:

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>

Using:

{"foo":"UGLY"}

Try it here:

http://tryhandlebarsjs.com/

Although it doesn't appear to let me save it. :(

这篇关于根据模板值将选定项目设置在选择列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆