我在使用 Meteor.js 输出所选复选框的值时遇到问题。复选框值在浏览器中输出为 [object Object]。有人可以帮我吗?
HTML
<head>
<title>project</title>
</head>
<body>
{{>addStatusForm}}
</body>
<template name="addStatusForm">
<form class="addStatus">
{{#each category}}
<input type="checkbox" name="categoryCheckbox" class="boxCheck" value={{categoryDesc}}>{{categoryDesc}}<br>
{{/each}}
<input type="text" name="status">
<input type="submit" value="Add status">
</form>
{{#each status}}
<p>{{statusDesc}} {{category}}</p>
{{/each}}
</template>
助手
Template.addStatusForm.helpers({
status: function () {
return Status.find();
},
category: function(){
return Category.find();
}
});
事件
Status = new Mongo.Collection('status');
Category = new Mongo.Collection('category');
Template.addStatusForm.events({
'submit .addStatus': function (event) {
event.preventDefault();
var statusInput = event.target.status.value;
var categorySelected = $('.boxCheck:checked').val();
//var categorySelected = event.target.categoryCheckbox.value; tried this
//var categorySelectedString = JSON.stringify(categorySelected); tried this also
//console.log(categorySelected); just testing console output
//console.log(statusInput); just testing console output
Status.insert({
statusDesc : statusInput,
category : categorySelected
});
}
最佳答案
问题不在于它的存储方式(console.log(typeofcategorySelected)
显示它是一个字符串而不是一个对象),而是您定义了“category”字段两次显示数据时在此模板中,一次来自助手,一次作为集合对象内部的字段。它使助手优先于集合数据,因此您可以获得从 return Category.find();
返回的对象,这是一个对象,因此是 [object Object] 输出
这里有两个快速解决方案:
A) 将 category
帮助器的名称更改为 categories
或其他名称
B)(可能更迅速)将每个代码内部的代码移动到状态模板中,给它一点隔离,这样它就看不到父模板类别字段
{{#each status}}
<p>{{statusDesc}} {{category}}</p>
{{/each}}
/*...BECOMES...*/
{{#each status}}
{{>statusTemplate}}
{{/each}}
<template name="statusTemplate">
<p>{{statusDesc}} {{category}}</p>
</template>
关于javascript - Meteor - 如何使用 Meteor.js 输出复选框值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35340298/