0

if anyone completed or is following David Turnbull's 'Creating your first Meteor app' this is a question from that.

On page 102 it says to "Add a “Score” field to the “Add Player” form, allowing users to define a score for a player when they’re being submitted to the list."

I figured out how to do it, using this in my leaderboard.js file:

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
    });
    var playerNameVar = event.target.playerName.value = "";
    var playerScoreVar = event.target.playerScore.value = "";
  }
});

And in my leaderboard.html file:

<template name="addPlayerForm">
  <form>
    <input type="text" name="playerName">
    <input type="number" name="playerScore">
    <input type="submit" value="Add Player">
   </form>
</template>

When a new player is created, the player is put at the top of the list regardless of their score. Which is sorted using this:

Template.leaderboard.helpers({
  'player': function(){
      return PlayersList.find({}, {sort: {score: -1, name: 1} });
      // -1 sorts descending, while 1 will sort ascending
  },
  ...
});

My guess is maybe I am not defining the score properly. Any help would be great!

MasterAM
  • 16,283
  • 6
  • 45
  • 66
Bart Dangus
  • 183
  • 1
  • 10

1 Answers1

1

The value of an input, even one with type="number", is still a string.

Therefore, if inserted as a string, it appears to have the highest value.

You should parse an int out of it and validate it:

var playerScoreVar = parseInt(event.target.playerScore.value, 10);
// validation logic may go here or be placed in a method.
...
MasterAM
  • 16,283
  • 6
  • 45
  • 66
  • Awesome. Thank you, I also found a couple other ways to do it: [right here](http://stackoverflow.com/questions/30223289/meteor-mongodb-insert-integer-instead-of-string-on-form-submit) – Bart Dangus Oct 30 '15 at 17:17