我正在学习如何使用 MeteorJS。我正在尝试用数据库的返回值预填表格,所有文本输入都没有问题,但我怎么能检查 radio 呢?我从数据库中得到的是一个很长的表格,至少有 150 个字段。所以我将不得不经常处理这个问题,但我不知道如何处理。显然,我已经检索到正确的文档,所有其他字段都很好, radio 的值也很好,但是我如何使用 Handlebars 或任何其他方式将选中的属性添加到它们。
Template.myTemp.helpers({
full : function () {
var id = Session.get('currentId');
if (id) {
return People.findOne({_id: id});
} else {
return true;
}
}
});
好的,所以这里返回 true 只是为了在没有定义 Session 的情况下显示没有预填充值的表单。接下来是我的模板的简短版本
<template name="myTemp">
{{#with full}}
<div class="input-field">
<label for="name" class="active">Name</label>
<input id="name" name="name" type="text" value= "{{name}}">
</div>
<p>
<input id="fem" name="sex" type="radio" value="FEM" class="with-gap">
<label for="fem">Female</label>
<input id="male" name="sex" type="radio" value="MALE" class="with-gap">
<label for="male">Male</label>
</p>
{{/with}}
</template>
所以这就是诀窍,当我使用此表单插入时效果很好,但在尝试预填充时,这是一场噩梦。如果我返回的值是来自以性别名称存储在数据库中的表单的值,我该如何检查此单选按钮。
最佳答案
我假设您的 People
集合的文档类似于以下对象:
{ "_id" : "adCsEGoHFbpJbFjtP", "name" : "John Doe", "sex" : "male" }
{ "_id" : "TYLDYicCzpHSD5Sk5", "name" : "Jane Doe", "sex" : "female" }
如果是这种情况,您可以在 myTemp
模板中定义一个助手,如果文档的属性 type
匹配,它会返回字符串 checked
函数的参数:
if (Meteor.isClient) {
Template.myTemp.helpers({
full: function () {
var id = Session.get('currentId');
if (id) return People.findOne({_id: id});
else return true;
},
isChecked: function (type) {
return (this && this.sex === type) ? 'checked' : null;
}
});
}
People = new Mongo.Collection("people");
if (Meteor.isServer) {
Meteor.startup(function () {
People.insert({
"name": "John Doe",
"sex": "male"
});
People.insert({
"name": "Jane Doe",
"sex": "female"
});
});
}
<template name="myTemp">
{{#with full}}
<div class="input-field">
<label for="name" class="active">Name</label>
<input id="name" name="name" type="text" value="{{name}}">
</div>
<p>
<input id="fem" name="sex" type="radio" value="FEM" class="with-gap" {{isChecked 'female'}}>
<label for="fem">Female</label>
<input id="male" name="sex" type="radio" value="MALE" class="with-gap" {{isChecked 'male'}}>
<label for="male">Male</label>
</p>
{{/with}}
</template>
这是一个MeteorPad .
关于javascript - 如果有的话, meteor 用数据库中的数据填充表格,如果没有则显示表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34037379/