【发布时间】:2014-11-27 06:34:35
【问题描述】:
在我的表单中,我创建了一个下拉列表以在用户键入时显示国家/地区列表。就目前而言,他们可以选择一个,单击“sublit”,然后通过流星调用将其插入到我的帖子集合中。下面的代码以及这个 jQuery 代码(保存在客户端文件夹中)是允许它运行的原因。使用的输入 ID 是“国家/地区”。
https://github.com/twitter/typeahead.js/blob/master/dist/typeahead.jquery.js
我的目标:仅允许将我的“国家”变量中列出的国家/地区插入数据库。我希望在我的方法函数中对此进行验证。
客户:
Template.createpost.rendered = function() {
if (!this.rendered){
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push({ value: str });
}
});
cb(matches);
};
};
var country = [
"Afghanistan",
"Albania",
"Algeria",
"Andorra",
"Angola",
"Antigua and Barbuda",
"Argentina",
"Rest Of Countries"
];
$('#country').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'country',
displayKey: 'value',
source: substringMatcher(country)
});
this.rendered = true;
}
};
Template.createpost.events({
'submit form#createpost': function(e, tmpl) {
e.preventDefault();
var insertPostData = {
country: $(e.target).find('#country').val()
}
Meteor.call('insertPostData', insertPostData, function(error, id){
if (error) {
alert(error.reason);
}
});
}
});
服务器:到目前为止,如果用户没有选择国家,我的方法只会引发错误。我不确定检查从客户收到的国家/地区值与我想在我的方法中列出的值数组的语法我愿意接受其他建议来实现这一点,请告诉我。谢谢各位。
Meteor.methods({
'insertPostData': function(insertPostData){
if (!insertPostData.country)
throw new Meteor.Error(422, 'please select valid country');
return insertPostData._id = AllPosts.insert(insertPostData);
}});
【问题讨论】:
-
看看Collection2!
标签: javascript jquery validation meteor typeahead.js