How to add three number fields in a form and show the result reactively (instantaneouly) at the bottom of the form in meteor

For eg: I have three fields in the form namely kid count, male count and female count. What I want is let’s say I give an input of 2 against kid count, 4 against male and 5 against female count. What I want is that as soon as I enter these inputs into the form, I want the resulting addition of these three numbers to be shown reactively against Total guest i.e 11.

This is my form:

GUEST

Male


Female


kids


          <h2>TOTAL GUESTS : <span>{{total}}</span> </h2>
          </div>

This is my helper function:

Template.pack1.helpers({
total: function(){
return Session.get(‘total’);
}
});

Lastly this is my event:

Template.pack1.events({
‘keyup .add’: function(event){

            var sum = event.target.value;
            Session.set('total', sum);
      }

});

The problem is I am not getting the desired output. The value being rendered against total guest is just the input I’m giving and not the sum of the three fields. I think I need to add something to make the sum variable contain the addition of three input values not just event.target.value. Please help!

You don’t really need any of Meteor’s tools for this. If you just want the number to be shown client side you can use a simple function that checks all fields and shows their sum in the box at the bottom.

Template.pack1.events({
	‘keyup .add’: function(event) {
		var sum = 0;
		$('.male, .female, .kids').forEach(f => {
			sum += parseInt(f.val(), 10);
		});

		$('.total').val(sum);
	}
});

In stead of the $('.total').val(sum); bit you can set it to a session variable there but I typically only use session variables if I’m going to need that value for some other logic down the line. Here, you’re just showing the user a total.

1 Like

It shows NaN when there’s empty string initially…can you suggest some checks for this so that it updates the value only when the parse function returns an integer otherwise not.

I’m still not sure this belongs in a Meteor forum. This is very basic javascript (or any other programming language for that matter) stuff.

You can take advantage of the fact that an empty string is a “falsy” value in Javascript. Therefor, f.val() || 0 will return 0 if f.val() is an empty string. Now if all three boxes are empty (which shouldn’t be the case because you should use number inputs with a min attribute of 0) the sum will be 0 + 0 + 0 = 0.

Instead of :

sum += parseInt(f.val(), 10); // isNaN( parseInt( '', 10 ) ) === true

Try this :

sum += ~~f.val();