Hitesh S
Hitesh S

Reputation: 580

Get values from two text-box and display sum of that on template in meteor.js

I'm trying to display sum value in template page using meteor.js.

Here is my html code:

<head>
    <title>Sum</title>
</head>
<body>
    <h1>Sum of two values</h1>

    {{> sumForm}}   
</body>

<template name="sumForm">
    <form>
        <input type="text" name="value1"> + <input type="text" name="value2"><p>Total: {{totalSum}}</p>
        <input type="submit" value="Sum">
    </form>
</template>

and my js code:

if(Meteor.isClient){

    Template.sumForm.events({

        'submit form': function(event){
            event.preventDefault();

            value1Var = parseInt(event.target.value1.value);
            value2Var = parseInt(event.target.value2.value);

            Template.sumForm.totalSum = value1Var + value2Var;

            return Template.sumForm.totalSum;           
        }
    });
} 

But this does not work.

Can any one help?

Upvotes: 1

Views: 1730

Answers (2)

mstamos
mstamos

Reputation: 111

You can user reactive-var to achive what you want

First you have to add the lightweight reactive-var package

meteor add reactive-var

Then at your Template file add:

if (Meteor.isClient) {
  Template.sumForm.created = function () {
    //We set default value
    this.counter = new ReactiveVar(0);
  }
  Template.sumForm.helpers({
    totalSum: function () {
     return Template.instance().counter.get();
    }
 });
 Template.sumForm.events({
   'submit form': function(event, template){
   event.preventDefault();

   value1Var = parseInt(event.target.value1.value);
   value2Var = parseInt(event.target.value2.value);

   var sum = value1Var + value2Var;
   return template.counter.set(sum);;
  }
 });
}

Upvotes: 1

jimmiebtlr
jimmiebtlr

Reputation: 444

Template.sumForm.helpers({
  totalSum: function(){
    return Session.get("sum");
  }    
});

And at the end of your submit event

Session.set("sum", value1Var + value2Var);

For a cleaner solution also consider using reactive-var instead of session variables.

Upvotes: 0

Related Questions