With a Handlebars.js template like this...
使用像这样的Handlebars.js模板......
<select>
<option value="Completed">Completed</option>
<option value="OverDue">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>
... and data like this...
......和这样的数据......
{
"id" : 1,
"name" : "World"
"status" : "OverDue",
"date" : "2012-12-21"
}
I want to render HTML like this.
我想像这样呈现HTML。
<select>
<option value="Completed">Completed</option>
<option value="OverDue" selected="selected">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>
Which way is the easiest?
哪种方式最简单?
14 个解决方案
#1
79
I found a lot of over complicated solutions and decided to write my own using a Handlebars helper.
我找到了很多过于复杂的解决方案,并决定使用Handlebars助手编写自己的解决方案。
With this partial (using Jquery) ...
有了这部分(使用Jquery)......
window.Handlebars.registerHelper('select', function( value, options ){
var $el = $('<select />').html( options.fn(this) );
$el.find('[value="' + value + '"]').attr({'selected':'selected'});
return $el.html();
});
You can wrap selects in your Handlebars template with {{#select status}}...
您可以使用{{#select status}}在Handlebars模板中包装选择...
<select>
{{#select status}}
<option value="Completed">Completed</option>
<option value="OverDue">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
{{/select}}
</select>
and end up with this...
并以此结束......
<select>
<option value="Completed">Completed</option>
<option value="OverDue" selected="selected">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>
Presto!
普雷斯托!
#2
27
I just had a similar need as the OP--with a static set of select options, but a dynamic selected value. I really like @janjarfalk's solution, but I'm using node.js and don't have jQuery pulled in. So, I put together my own variation based on RegExp's. Hope this is helpful to others.
我只是有与OP相似的需求 - 有一组静态的选择选项,但是是一个动态选择值。我真的很喜欢@ janjarfalk的解决方案,但是我使用的是node.js并没有拉入jQuery。所以,我根据RegExp将我自己的变体放在一起。希望这对其他人有帮助。
Handlebars helper:
把手帮手:
hbs.registerHelper('select', function(selected, options) {
return options.fn(this).replace(
new RegExp(' value=\"' + selected + '\"'),
'$& selected="selected"');
});
Handlebars template:
把手模板:
<select>
{{#select CurrentSort}}
<option value="1">Most Recent First</option>
<option value="2">Most Recent Last</option>
<option value="3">Highest Score First</option>
<option value="4">Highest Score Last</option>
<option value="5">Most Comments</option>
<option value="6">Fewest Comments</option>
<option value="7">Most Helpful Votes</option>
<option value="8">Fewest Helpful Votes</option>
{{/select}}
</select>
You can tweak the helper to work even if you don't use the value
attribute--just adjust the regexp to search the element text, and do the string replacement before the matched text.
即使您不使用value属性,也可以调整帮助程序 - 只需调整正则表达式以搜索元素文本,并在匹配的文本之前执行字符串替换。
#3
16
I saw the extremely clever solution posted by @janjarfalk and realized it didn't work for options defined without a value attribute (such as <option>Value</option>
). My application needed that, and I wanted a helper done in vanilla JavaScript for performance, so I came up with the following.
我看到了@janjarfalk发布的非常聪明的解决方案,并意识到它不适用于没有值属性定义的选项(例如
This solution will support <option>Both a label and a value</option>
in addition to <option value="aValue">A label</option>
and will be much faster as it doesn't use jQuery.
除
Handlebars.registerHelper('select', function(value, options) {
// Create a select element
var select = document.createElement('select');
// Populate it with the option HTML
select.innerHTML = options.fn(this);
// Set the value
select.value = value;
// Find the selected node, if it exists, add the selected attribute to it
if (select.children[select.selectedIndex])
select.children[select.selectedIndex].setAttribute('selected', 'selected');
return select.innerHTML;
});
Usage:
用法:
<select>
{{#select status}}
<option>Option 1</option>
<option>Option 2</option>
<option value="Option 3">Option 3 (extra info)</option>
<option value="Option 4">Option 4 (more extra)</option>
{{/select}}
</select>
#4
9
I've had problems with the "select block" approach when using the "each" helper to build something dynamic, due to the context.
由于上下文的原因,在使用“每个”帮助器构建动态内容时,我遇到了“选择块”方法的问题。
Here is my solution:
这是我的解决方案:
Handlebars.registerHelper('option', function(value, label, selectedValue) {
var selectedProperty = value == selectedValue ? 'selected="selected"' : '';
return new Handlebars.SafeString('<option value="' + value + '"' + selectedProperty + '>' + label + "</option>");
});
And the template:
和模板:
<select>
{{#each status}}
{{option id name ../statusId}}
{{/each}}
</select>
#5
6
Improved answer of @lazd to select first option when nothing matches.
改进@lazd的答案,在没有匹配时选择第一个选项。
Handlebars.registerHelper('select', function(value, options) {
// Create a select element
var select = document.createElement('select');
// Populate it with the option HTML
$(select).html(options.fn(this));
//below statement doesn't work in IE9 so used the above one
//select.innerHTML = options.fn(this);
// Set the value
select.value = value;
// Find the selected node, if it exists, add the selected attribute to it
if (select.children[select.selectedIndex]) {
select.children[select.selectedIndex].setAttribute('selected', 'selected');
} else { //select first option if that exists
if (select.children[0]) {
select.children[0].setAttribute('selected', 'selected');
}
}
return select.innerHTML;
});
Usage remains same:
用法保持不变:
<select>
{{#select status}}
<option>Option 1</option>
<option>Option 2</option>
<option value="Option 3">Option 3 (extra info)</option>
<option value="Option 4">Option 4 (more extra)</option>
{{/select}}
</select>
#6
6
Works for me
适合我
<select>
<option value="{{status}}" hidden="hidden" selected="selected">{{status}}</option>
<option value="Completed">Completed</option>
<option value="OverDue">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>
#7
2
I just ran into this problem, here's a solution for when the options are dynamic..
我刚遇到这个问题,这里的选项是动态的解决方案。
Instead of creating a select helper, I created an option helper that accepts the value of the item you wish to be selected.
我创建了一个选项助手,而不是创建一个选择助手,它接受您希望选择的项目的值。
Handlebars.registerHelper('option', function(value) {
var selected = value.toLowerCase() === (this.toString()).toLowerCase() ? 'selected="selected"' : '';
return '<option value="' + this + '" ' + selected + '>' + this + '</option>';
});
And in my template.
在我的模板中。
{{#items}}
{{{option ../selected_value}}}
{{/items}}
Please note the ../ to access the parent's scope as it's not likely the selected_value will be inside of the items array.
请注意../访问父级的范围,因为selected_value不太可能在items数组中。
Cheers.
干杯。
#8
2
I prefer to use a template approach. By this I mean the layout of the option tag itself is specified in the handlebars template (where someone might look for it) and not in the javascript helper. Template inside the block helper is passed into the helper script and can be used by calling options.fn() which then uses any script changes you have made in your helper.
我更喜欢使用模板方法。我的意思是选项标签本身的布局是在把手模板中指定的(有人可能会找到它),而不是在javascript帮助器中。块帮助程序内的模板传递给帮助程序脚本,可以通过调用options.fn()来使用,然后使用您在帮助程序中进行的任何脚本更改。
Template:
模板:
<select>
{{#optionsList aStatusList sCurrentStatusCode 'statusCode'}}
<option {{isSelected}} value="{{statusCode}}">{{statusName}}</option>
{{/optionsList}}
</select>
Slightly modified data (not required but a little more "real world" for me)
略有修改的数据(不是必需的,但对我来说更多“现实世界”)
var myOrder =
{
"id" : 1,
"name" : "World",
"statusName" : "OverDue", /* status should NOT be here! */
"statusCode" : "1",
"date" : "2012-12-21"
}
var sCurrentStatusCode = myOrder.statusCode;
var aStatusList =
[
{
"statusName" : "Node",
"statusCode" : 0
},
{
"statusName" : "Overdue",
"statusCode" : 1
},
{
"statusName" : "Completed",
"statusCode" : 2
},
{
"statusName" : "Sent to Payer",
"statusCode" : 3
}
]
Javascript registered helper:
Javascript注册帮助:
Handlebars.registerHelper( 'optionsList',
function ( aOptions, sSelectedOptionValue, sOptionProperty, options )
{
var out = "";
for ( var i = 0, l = aOptions.length; i < l; i++ )
{
aOptions[ i ].isSelected = '';
if( ( sOptionProperty != null && sSelectedOptionValue == aOptions[ i ][ sOptionProperty ] ) || ( sSelectedOptionValue == aOptions[ i ] ) )
{
aOptions[ i ].isSelected = ' selected="selected" ';
}
out = out + options.fn( aOptions[ i ] );
}
return out;
} );
optionsList is what I have chosen to name this helper
optionsList是我选择命名这个帮助器的方法
aStatusList an array of status objects contain several properties including the status value/name (in most cases I have encountered this would be the status code not the status name that is stored )
aStatusList一个状态对象数组包含几个属性,包括状态值/名称(在大多数情况下,我遇到过这将是状态代码而不是存储的状态名称)
sCurrentStatus is the previously selected status code (not the value) and is the option value that i would like to have the selected in this generated option list.
sCurrentStatus是先前选择的状态代码(不是值),是我希望在此生成的选项列表中选择的选项值。
statusCode is the string property name within a aStatusList object that I will test to see if it matches myStatus that is aStutusList[ loopIndex ][statusCode]
statusCode是aStatusList对象中的字符串属性名称,我将测试它是否匹配myStatus是aStutusList [loopIndex] [statusCode]
- the string option property ( statusCode in this case ) is only required for objects -- options lists may also be arrays of strings (instead of objects that in turn containing strings) in which case you may omit the the third property 'statusCode' which tells the helper what property of the object to test agains. If you don't pass that property it will just test againts the list item itself.
- 只有对象才需要字符串选项属性(在本例中为statusCode) - 选项列表也可以是字符串数组(而不是包含字符串的对象),在这种情况下,您可以省略第三个属性'statusCode',它告诉帮助器对象的哪些属性要再次测试。如果你没有传递那个属性,它只会测试列表项本身。
- if the sSelectedOptionValue is not passed then the list will be produced without setting any item to selected. This will generate the list pretty much the same as using the {{#each}} helper
- 如果未传递sSelectedOptionValue,则将生成列表而不设置任何项目。这将生成与使用{{#each}}帮助器几乎相同的列表
#9
1
If you have very few options and you don't want to write a helper, here is what you can do:
如果您选择的选项很少而且您不想编写帮助程序,那么您可以执行以下操作:
//app.js
var data = {selectedVal: 'b'};
// can also use switch ... case ...
if (data.selectedVal === 'a') {
data.optionASelected = true;
} else if (data.selectedVal === 'b') {
data.optionBSelected = true;
}
// assuming you have a template function to handle this data
templateFunc(data);
In your template file:
在您的模板文件中:
<!-- template.html -->
<select id="select-wo-helper" >
<option value="a" {{#if optionASelected}} selected {{/if}}>A</option>
<option value="b" {{#if optionBSelected}} selected {{/if}}>B</option>
</select>
Again this may NOT be the best solution of all, but it probably is a very quick work around when you are dealing very few options and wanted a quick fix.
同样,这可能不是最好的解决方案,但是当你处理很少的选项并希望快速解决时,它可能是一个非常快速的解决方案。
#10
1
This might take more code in the template, but it is easier to read:
这可能会在模板中占用更多代码,但更容易阅读:
.js
.js文件
Handlebars.registerHelper('select', function(selected, option) {
return (selected == option) ? 'selected="selected"' : '';
});
.hbs
.hbs
<select name="status">
<option value="public" {{{select story.status 'public'}}}>Public</option>
<option value="private" {{{select story.status 'private'}}}>Private</option>
<option value="unpublished" {{{select story.status 'unpublished'}}}>Unpublished</option>
</select>
#11
0
It should be mentioned that if you do not care about repeats... you can just use vanilla handlebars and place the selected option first, such as:
应该提到的是,如果你不关心重复......你可以使用香草把手并首先放置所选的选项,例如:
<select name="ingredient">
<option value="{{ingredient.id}}" selected>{{ingredient.name}}</option>
{{#each ingredients}}
<option value="{{this.id}}">{{this.name}}</option>
{{/each}}
</select>
#12
0
@lazd's answer does not work for <option>
elements within an <optgroup>
.
@ lazd的答案不适用于
selectedIndex
is numbered monotonically for all <option>
s, but select.children
holds the <optgroup>
s, and select.children[n].children
holds the <option>
s within <optgroup>
n (with numbering restarting within each <optgroup>
, of course).
selectedIndex对所有
This alternative version will work for <option>
elements within <optgroup>
s:
此替代版本适用于
Handlebars.registerHelper('select-optgrp', function(value, options) {
var select = document.createElement('select'); // create a select element
select.innerHTML = options.fn(this); // populate it with the option HTML
select.value = value; // set the value
var g = 0, i = select.selectedIndex; // calculate which index of which optgroup
while (i >= select.children[g].children.length) { i -= select.children[g].children.length; g++; }
if (select.children[g].children[i]) { // if selected node exists add 'selected' attribute
select.children[g].children[i].setAttribute('selected', true);
}
return select.innerHTML;
});
#13
0
Another one solution using express-handlebars
and dynamic options is this.
另一种使用快速把手和动态选项的解决方案就是这样。
Helper function (From all options takes the one we want and change it to selected).
辅助功能(从所有选项中取出我们想要的选项并将其更改为选中)。
select: function(selected, options) {
return options.fn(this)
.replace( new RegExp(' value=\"' + selected + '\"'), '$& selected="selected"')
.replace( new RegExp('>' + selected + '</option>'), ' selected="selected"$&');
}
handlebars file (I just use #each inside select to receive me data and worked like a charm).
把手文件(我只是使用#each inside select来接收我的数据,并像魅力一样工作)。
<select name="justAname">
{{#select content.campusId}}
{{#each campus}}
<option value="{{id}}">{{name}}</option>
{{/each}}
{{/select}}
</select>
#14
0
Handlebars.registerHelper('select', function( value, options ){
return options.fn(this)
.replace( new RegExp(' value=\"' + value + '\"'), '$& selected="selected"')
.replace( new RegExp('>' + value + '</option>'), ' selected="selected"$&');
});
user.country from db session
country stored in country.json file
<select id="country" name="country" class="form-control">
<option value="" selected="selected">(please select a country)</option>
{{#select user.country}}
{{#each countries as |value key| }}
<option value="{{ value.code }}">{{ value.name }}</option>
{{/each}}
{{/select}}
</select>
#1
79
I found a lot of over complicated solutions and decided to write my own using a Handlebars helper.
我找到了很多过于复杂的解决方案,并决定使用Handlebars助手编写自己的解决方案。
With this partial (using Jquery) ...
有了这部分(使用Jquery)......
window.Handlebars.registerHelper('select', function( value, options ){
var $el = $('<select />').html( options.fn(this) );
$el.find('[value="' + value + '"]').attr({'selected':'selected'});
return $el.html();
});
You can wrap selects in your Handlebars template with {{#select status}}...
您可以使用{{#select status}}在Handlebars模板中包装选择...
<select>
{{#select status}}
<option value="Completed">Completed</option>
<option value="OverDue">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
{{/select}}
</select>
and end up with this...
并以此结束......
<select>
<option value="Completed">Completed</option>
<option value="OverDue" selected="selected">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>
Presto!
普雷斯托!
#2
27
I just had a similar need as the OP--with a static set of select options, but a dynamic selected value. I really like @janjarfalk's solution, but I'm using node.js and don't have jQuery pulled in. So, I put together my own variation based on RegExp's. Hope this is helpful to others.
我只是有与OP相似的需求 - 有一组静态的选择选项,但是是一个动态选择值。我真的很喜欢@ janjarfalk的解决方案,但是我使用的是node.js并没有拉入jQuery。所以,我根据RegExp将我自己的变体放在一起。希望这对其他人有帮助。
Handlebars helper:
把手帮手:
hbs.registerHelper('select', function(selected, options) {
return options.fn(this).replace(
new RegExp(' value=\"' + selected + '\"'),
'$& selected="selected"');
});
Handlebars template:
把手模板:
<select>
{{#select CurrentSort}}
<option value="1">Most Recent First</option>
<option value="2">Most Recent Last</option>
<option value="3">Highest Score First</option>
<option value="4">Highest Score Last</option>
<option value="5">Most Comments</option>
<option value="6">Fewest Comments</option>
<option value="7">Most Helpful Votes</option>
<option value="8">Fewest Helpful Votes</option>
{{/select}}
</select>
You can tweak the helper to work even if you don't use the value
attribute--just adjust the regexp to search the element text, and do the string replacement before the matched text.
即使您不使用value属性,也可以调整帮助程序 - 只需调整正则表达式以搜索元素文本,并在匹配的文本之前执行字符串替换。
#3
16
I saw the extremely clever solution posted by @janjarfalk and realized it didn't work for options defined without a value attribute (such as <option>Value</option>
). My application needed that, and I wanted a helper done in vanilla JavaScript for performance, so I came up with the following.
我看到了@janjarfalk发布的非常聪明的解决方案,并意识到它不适用于没有值属性定义的选项(例如
This solution will support <option>Both a label and a value</option>
in addition to <option value="aValue">A label</option>
and will be much faster as it doesn't use jQuery.
除
Handlebars.registerHelper('select', function(value, options) {
// Create a select element
var select = document.createElement('select');
// Populate it with the option HTML
select.innerHTML = options.fn(this);
// Set the value
select.value = value;
// Find the selected node, if it exists, add the selected attribute to it
if (select.children[select.selectedIndex])
select.children[select.selectedIndex].setAttribute('selected', 'selected');
return select.innerHTML;
});
Usage:
用法:
<select>
{{#select status}}
<option>Option 1</option>
<option>Option 2</option>
<option value="Option 3">Option 3 (extra info)</option>
<option value="Option 4">Option 4 (more extra)</option>
{{/select}}
</select>
#4
9
I've had problems with the "select block" approach when using the "each" helper to build something dynamic, due to the context.
由于上下文的原因,在使用“每个”帮助器构建动态内容时,我遇到了“选择块”方法的问题。
Here is my solution:
这是我的解决方案:
Handlebars.registerHelper('option', function(value, label, selectedValue) {
var selectedProperty = value == selectedValue ? 'selected="selected"' : '';
return new Handlebars.SafeString('<option value="' + value + '"' + selectedProperty + '>' + label + "</option>");
});
And the template:
和模板:
<select>
{{#each status}}
{{option id name ../statusId}}
{{/each}}
</select>
#5
6
Improved answer of @lazd to select first option when nothing matches.
改进@lazd的答案,在没有匹配时选择第一个选项。
Handlebars.registerHelper('select', function(value, options) {
// Create a select element
var select = document.createElement('select');
// Populate it with the option HTML
$(select).html(options.fn(this));
//below statement doesn't work in IE9 so used the above one
//select.innerHTML = options.fn(this);
// Set the value
select.value = value;
// Find the selected node, if it exists, add the selected attribute to it
if (select.children[select.selectedIndex]) {
select.children[select.selectedIndex].setAttribute('selected', 'selected');
} else { //select first option if that exists
if (select.children[0]) {
select.children[0].setAttribute('selected', 'selected');
}
}
return select.innerHTML;
});
Usage remains same:
用法保持不变:
<select>
{{#select status}}
<option>Option 1</option>
<option>Option 2</option>
<option value="Option 3">Option 3 (extra info)</option>
<option value="Option 4">Option 4 (more extra)</option>
{{/select}}
</select>
#6
6
Works for me
适合我
<select>
<option value="{{status}}" hidden="hidden" selected="selected">{{status}}</option>
<option value="Completed">Completed</option>
<option value="OverDue">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>
#7
2
I just ran into this problem, here's a solution for when the options are dynamic..
我刚遇到这个问题,这里的选项是动态的解决方案。
Instead of creating a select helper, I created an option helper that accepts the value of the item you wish to be selected.
我创建了一个选项助手,而不是创建一个选择助手,它接受您希望选择的项目的值。
Handlebars.registerHelper('option', function(value) {
var selected = value.toLowerCase() === (this.toString()).toLowerCase() ? 'selected="selected"' : '';
return '<option value="' + this + '" ' + selected + '>' + this + '</option>';
});
And in my template.
在我的模板中。
{{#items}}
{{{option ../selected_value}}}
{{/items}}
Please note the ../ to access the parent's scope as it's not likely the selected_value will be inside of the items array.
请注意../访问父级的范围,因为selected_value不太可能在items数组中。
Cheers.
干杯。
#8
2
I prefer to use a template approach. By this I mean the layout of the option tag itself is specified in the handlebars template (where someone might look for it) and not in the javascript helper. Template inside the block helper is passed into the helper script and can be used by calling options.fn() which then uses any script changes you have made in your helper.
我更喜欢使用模板方法。我的意思是选项标签本身的布局是在把手模板中指定的(有人可能会找到它),而不是在javascript帮助器中。块帮助程序内的模板传递给帮助程序脚本,可以通过调用options.fn()来使用,然后使用您在帮助程序中进行的任何脚本更改。
Template:
模板:
<select>
{{#optionsList aStatusList sCurrentStatusCode 'statusCode'}}
<option {{isSelected}} value="{{statusCode}}">{{statusName}}</option>
{{/optionsList}}
</select>
Slightly modified data (not required but a little more "real world" for me)
略有修改的数据(不是必需的,但对我来说更多“现实世界”)
var myOrder =
{
"id" : 1,
"name" : "World",
"statusName" : "OverDue", /* status should NOT be here! */
"statusCode" : "1",
"date" : "2012-12-21"
}
var sCurrentStatusCode = myOrder.statusCode;
var aStatusList =
[
{
"statusName" : "Node",
"statusCode" : 0
},
{
"statusName" : "Overdue",
"statusCode" : 1
},
{
"statusName" : "Completed",
"statusCode" : 2
},
{
"statusName" : "Sent to Payer",
"statusCode" : 3
}
]
Javascript registered helper:
Javascript注册帮助:
Handlebars.registerHelper( 'optionsList',
function ( aOptions, sSelectedOptionValue, sOptionProperty, options )
{
var out = "";
for ( var i = 0, l = aOptions.length; i < l; i++ )
{
aOptions[ i ].isSelected = '';
if( ( sOptionProperty != null && sSelectedOptionValue == aOptions[ i ][ sOptionProperty ] ) || ( sSelectedOptionValue == aOptions[ i ] ) )
{
aOptions[ i ].isSelected = ' selected="selected" ';
}
out = out + options.fn( aOptions[ i ] );
}
return out;
} );
optionsList is what I have chosen to name this helper
optionsList是我选择命名这个帮助器的方法
aStatusList an array of status objects contain several properties including the status value/name (in most cases I have encountered this would be the status code not the status name that is stored )
aStatusList一个状态对象数组包含几个属性,包括状态值/名称(在大多数情况下,我遇到过这将是状态代码而不是存储的状态名称)
sCurrentStatus is the previously selected status code (not the value) and is the option value that i would like to have the selected in this generated option list.
sCurrentStatus是先前选择的状态代码(不是值),是我希望在此生成的选项列表中选择的选项值。
statusCode is the string property name within a aStatusList object that I will test to see if it matches myStatus that is aStutusList[ loopIndex ][statusCode]
statusCode是aStatusList对象中的字符串属性名称,我将测试它是否匹配myStatus是aStutusList [loopIndex] [statusCode]
- the string option property ( statusCode in this case ) is only required for objects -- options lists may also be arrays of strings (instead of objects that in turn containing strings) in which case you may omit the the third property 'statusCode' which tells the helper what property of the object to test agains. If you don't pass that property it will just test againts the list item itself.
- 只有对象才需要字符串选项属性(在本例中为statusCode) - 选项列表也可以是字符串数组(而不是包含字符串的对象),在这种情况下,您可以省略第三个属性'statusCode',它告诉帮助器对象的哪些属性要再次测试。如果你没有传递那个属性,它只会测试列表项本身。
- if the sSelectedOptionValue is not passed then the list will be produced without setting any item to selected. This will generate the list pretty much the same as using the {{#each}} helper
- 如果未传递sSelectedOptionValue,则将生成列表而不设置任何项目。这将生成与使用{{#each}}帮助器几乎相同的列表
#9
1
If you have very few options and you don't want to write a helper, here is what you can do:
如果您选择的选项很少而且您不想编写帮助程序,那么您可以执行以下操作:
//app.js
var data = {selectedVal: 'b'};
// can also use switch ... case ...
if (data.selectedVal === 'a') {
data.optionASelected = true;
} else if (data.selectedVal === 'b') {
data.optionBSelected = true;
}
// assuming you have a template function to handle this data
templateFunc(data);
In your template file:
在您的模板文件中:
<!-- template.html -->
<select id="select-wo-helper" >
<option value="a" {{#if optionASelected}} selected {{/if}}>A</option>
<option value="b" {{#if optionBSelected}} selected {{/if}}>B</option>
</select>
Again this may NOT be the best solution of all, but it probably is a very quick work around when you are dealing very few options and wanted a quick fix.
同样,这可能不是最好的解决方案,但是当你处理很少的选项并希望快速解决时,它可能是一个非常快速的解决方案。
#10
1
This might take more code in the template, but it is easier to read:
这可能会在模板中占用更多代码,但更容易阅读:
.js
.js文件
Handlebars.registerHelper('select', function(selected, option) {
return (selected == option) ? 'selected="selected"' : '';
});
.hbs
.hbs
<select name="status">
<option value="public" {{{select story.status 'public'}}}>Public</option>
<option value="private" {{{select story.status 'private'}}}>Private</option>
<option value="unpublished" {{{select story.status 'unpublished'}}}>Unpublished</option>
</select>
#11
0
It should be mentioned that if you do not care about repeats... you can just use vanilla handlebars and place the selected option first, such as:
应该提到的是,如果你不关心重复......你可以使用香草把手并首先放置所选的选项,例如:
<select name="ingredient">
<option value="{{ingredient.id}}" selected>{{ingredient.name}}</option>
{{#each ingredients}}
<option value="{{this.id}}">{{this.name}}</option>
{{/each}}
</select>
#12
0
@lazd's answer does not work for <option>
elements within an <optgroup>
.
@ lazd的答案不适用于
selectedIndex
is numbered monotonically for all <option>
s, but select.children
holds the <optgroup>
s, and select.children[n].children
holds the <option>
s within <optgroup>
n (with numbering restarting within each <optgroup>
, of course).
selectedIndex对所有
This alternative version will work for <option>
elements within <optgroup>
s:
此替代版本适用于
Handlebars.registerHelper('select-optgrp', function(value, options) {
var select = document.createElement('select'); // create a select element
select.innerHTML = options.fn(this); // populate it with the option HTML
select.value = value; // set the value
var g = 0, i = select.selectedIndex; // calculate which index of which optgroup
while (i >= select.children[g].children.length) { i -= select.children[g].children.length; g++; }
if (select.children[g].children[i]) { // if selected node exists add 'selected' attribute
select.children[g].children[i].setAttribute('selected', true);
}
return select.innerHTML;
});
#13
0
Another one solution using express-handlebars
and dynamic options is this.
另一种使用快速把手和动态选项的解决方案就是这样。
Helper function (From all options takes the one we want and change it to selected).
辅助功能(从所有选项中取出我们想要的选项并将其更改为选中)。
select: function(selected, options) {
return options.fn(this)
.replace( new RegExp(' value=\"' + selected + '\"'), '$& selected="selected"')
.replace( new RegExp('>' + selected + '</option>'), ' selected="selected"$&');
}
handlebars file (I just use #each inside select to receive me data and worked like a charm).
把手文件(我只是使用#each inside select来接收我的数据,并像魅力一样工作)。
<select name="justAname">
{{#select content.campusId}}
{{#each campus}}
<option value="{{id}}">{{name}}</option>
{{/each}}
{{/select}}
</select>
#14
0
Handlebars.registerHelper('select', function( value, options ){
return options.fn(this)
.replace( new RegExp(' value=\"' + value + '\"'), '$& selected="selected"')
.replace( new RegExp('>' + value + '</option>'), ' selected="selected"$&');
});
user.country from db session
country stored in country.json file
<select id="country" name="country" class="form-control">
<option value="" selected="selected">(please select a country)</option>
{{#select user.country}}
{{#each countries as |value key| }}
<option value="{{ value.code }}">{{ value.name }}</option>
{{/each}}
{{/select}}
</select>