0

I'm writing a simple program to teach the basic of input, form and template and sessions using Meteor.

 if (Meteor.isClient) {

 Session.set('value',0);


 Template.hello.helpers({

 result: function(){

  return(Session.get('value'));
}
});


Template.hello.events({

 'submit form': function(event) {

  event.preventDefault();

  var s1=event.target.num1.value;
  var s2=event.target.num2.value;

  var s = s1 - s2;

 Session.set('value',s);

}

}); }

The problem is when the operator is changed to + it seems to concatenate the two numbers. Other basic operators work fine. It is a bug ? This is the simplest example I can teach to my students and I get stuck.

I'm using Mac 10.6.8 and Meteor 1.1.0.2

Zahar
  • 11
  • 1
  • possible duplicate of [Why does JavaScript handle the plus and minus operators between strings and numbers differently?](http://stackoverflow.com/questions/24383788/why-does-javascript-handle-the-plus-and-minus-operators-between-strings-and-numb) // absolutely not meteor-specific btw. – CBroe Jul 11 '15 at 04:20

2 Answers2

0

It's hard to tell without seeing a JSFiddle but I bet you the problem is that one of the values or both is being passed in as a string.

The plus sign is the concatenation operator for JS and will perform type coercion from a number to a string, if both are not numbers and one is a string. The - operator will perform it the other way, and turn strings into numbers.

Check the data types being passed in and makes sure they're both numbers. If they aren't, use parseInt to turn them into numbers.

whatoncewaslost
  • 2,216
  • 2
  • 17
  • 25
0

string + string = string.

Try this:

  var s1=+event.target.num1.value;
  var s2=+event.target.num2.value;

Always turn your strings to numbers when you take them from the DOM.

Matt K
  • 4,813
  • 4
  • 22
  • 35