1 Replies - 622 Views - Last Post: 24 January 2012 - 06:58 PM

#1 3t3rn1ty  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 24-January 12

How to store text/numbers from a text field into a JS variable.

Posted 24 January 2012 - 05:37 PM

I only need help in starting this assignment. I need to create a text field and a submit button in HTML. I need to receive fourteen numbers one at a time and store them in a variable so that later I can do some calculations with those numbers. What I was thinking is that I could put the numbers into an array as the numbers are being given.
Is This A Good Question/Topic? 0
  • +

Replies To: How to store text/numbers from a text field into a JS variable.

#2 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: How to store text/numbers from a text field into a JS variable.

Posted 24 January 2012 - 06:58 PM

Do you know how to use the DOM? That is, how to use functions like document.getElementById to find elements?

Quote

What I was thinking is that I could put the numbers into an array as the numbers are being given.

That's a good idea. You can easily push new elements into an array using the Array.push method. An example of this would be:
var myArray = [];
for (var i = 0; i < 10; ++i) {
    myArray.push(Math.random());
}


Now you have 10 random numbers in the array, indexed 0 through 9.

Other useful methods to consider when dealing with user supplied numbers:

  • parseInt turns strings into actual numbers. Use this on user supplied input if you want to use the numbers in calculations.

  • parseFloat does the same thing as parseInt, except it can handle fractions, which parseInt cant.

  • isNaN makes sure that the numbers the parse functions return are actually numbers. If the user input can't be parsed into numbers, the parse functions will return a NaN instead of a number, and this function checks for that. I strongly recommend using this function any time you parse a string into a number. Can save you a lot of debugging later on.

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1