【问题标题】:How to add two inputs from the same forms in the same collection field in Meteor?如何在 Meteor 的同一集合字段中添加来自相同表单的两个输入?
【发布时间】:2016-01-15 02:32:35
【问题描述】:

我正在为我的第一个应用编写流星教程。所以我想进一步扩展它,并有两个文本框,一个用于 cmets,一个用于评级。 问题是我无法从两种表单中正确获取值(实际上根本无法获取评级值),以便将它们保存在我的数据库中,而且输入提交功能停止工作。

我的正文事件的 .js 代码是:

Template.body.events({
    "submit .new-task": function(event) {
        // Prevent default browser form submit
        event.preventDefault();

        // Get value from form element
        var text = event.target.text.value;
        var rating = event.target.rating.value;

        // Insert a task into the collection
        Meteor.call("addTask", text, rating);

        // Clear form
        event.target.text.value = "";

    }
});

添加任务:

AddTask: function(text, rating) {
    //.....
    Tasks.insert({
        text: text,
        createdAt: new Date(),
        owner: Meteor.userId(),
        username: Meteor.user().username,
        rating: rating
    });
}

还有我的 HTML:

<form class="new-task">
    <h2>What is happening?</h2>
    <input type="text" name="text" placeholder="Share your experience!" />
    <h2>Rating:</h2>
    <input type="text" name="rating" placeholder="insert your rating!" />
</form>

<template name="task">
    <li class="{{#if checked}}checked{{/if}}">
        {{#if isOwner}}
        <button class="delete">&times;</button>
        {{/if}}
        <span class="text"><strong>{{username}}</strong> - {{text}}- {{rating}}</span>
    </li>
</template>

【问题讨论】:

  • 不确定你的文件名是什么,但Template.body.events 可能会丢掉一些东西,除非你的模板被命名为body
  • 点赞&lt;template name="body"&gt; ~ some stuff ~ &lt;/template&gt;
  • 如果是任务,则需要类似于Template.task.events
  • 我没有一个名为 body 的模板,但流星的代码也没有,它工作正常。我所做的唯一补充是:1)var rating = event.target.rating.value; 2)

    评分:

    3)评分:评分

标签: javascript html mongodb meteor meteor-helper


【解决方案1】:

您的 Meteor 方法 addTask 未定义。请改为调用Meteor.call("AddTask", text, rating);,或将您的方法重命名为addTask

例如:

if (Meteor.isClient) {
    Template.hello.events({
        'click button': function () {
            Meteor.call("addTask", "1", 2, function(error){
                if (error) alert(error.reason);
            });
        }
    });
}

if (Meteor.isServer) {
    Meteor.methods({
        addTask: function (text, rating) {
            check(text, String);
            check(rating, Number);
            console.log(text);
            console.log(rating);
        }
    });
}

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 2016-03-27
    • 2016-01-24
    • 2022-11-25
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多