Search code examples
javascripthtmlmongodbmeteormeteor-helper

How to add two inputs from the same forms in the same collection field in Meteor?


Im working on the tutorial meteor has for my first app. So i wanted to extend it a bit more and have two text boxes, one for comments and one for rating lets say. The problem is that i cant get correctly the values from both forms (actually cant get the rating value at all) in order to save them in my database and furthermore the enter-submit feature stopped working.

My .js code for body events is:

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 = "";

    }
});

For add task:

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

And my 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>

Solution

  • Your Meteor method addTask is not defined. Call Meteor.call("AddTask", text, rating); instead, or rename your method to addTask.

    For example:

    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);
            }
        });
    }