5

I'm working through David's tutorial on Meteor at http://meteortips.com/.

How do I insert an integer instead of string on form submit?

I think the following line needs to clarify that it's an integer, but I'm not sure how.

var playerScoreVar = event.target.playerScore.value;

Here's my whole code.

 Template.addPlayerForm.events({

  'submit form': function(event){
      event.preventDefault();
      var playerNameVar = event.target.playerName.value;
      var playerScoreVar = event.target.playerScore.value;
      PlayersList.insert({
          name: playerNameVar,
          score: playerScoreVar,
      });
      event.target.playerName.value = ""
      event.target.playerScore.value = ""
  }
});
Agent Zebra
  • 4,410
  • 6
  • 33
  • 66

1 Answers1

4

Just convert it to an integer prior to the insert:

var playerScoreVar = parseInt(event.target.playerScore.value, 10);

or

var playerScoreVar = Number(event.target.playerScore.value);

You can see the differences explained here;

Community
  • 1
  • 1
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • Thanks, what does the 10 mean on the end of that line? And why can't I just write 'Int' somewhere in that line and be done with it? :D – Agent Zebra May 13 '15 at 19:11
  • 1
    It's the radix (base). See the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt). – David Weldon May 13 '15 at 19:12
  • Got it, so I either have to parseInt or make sure they're only putting numbers in the form element in the first place. Thanks. – Agent Zebra May 13 '15 at 19:15
  • 1
    Whenever you extract the value from an input it will be a string, so you'll have to do the conversion. And yes, you probably want some other kind of form validation on top of this. – David Weldon May 13 '15 at 19:18