Treating text input from a form as an integer or float

If you have completed the User Input with Forms tutorial, you will now know how to ask the user for text input through a form, and use that input in some way. However, if you trying collecting input from the user in the form of numbers and then try to do some logical operations on those numbers, you may run into problems.

The first problem is that any text input will be treated as a string, not an integer. So if you try to compare two numbers eg. check if the inputted number is equal to 5, JavaScript will be trying to check if a string input is equal to a number and will not be checking if an integer input is equal to a specific integer.

The video and sample code below shows an example of using parseInt() to treat text input from a textbox as an integer value. You can also use parseFloat() to parse a string as a float (real number with decimal places). The video also shows how to grab the value from a textbox by using document.getElementById(‘idname’).value so that a logical operation can happen

The example used in the video and the code below is a simple math question game. The program displays a math problem to the user. The user can enter their answer in a textbox and the page will display a message if the user gets the correct answer. Watch the video below to see how to write the code for this program.

Once you have completed the tutorial, your program should work like this:


Here is the code for the program:

<title>Simple math game</title>
<script type="text/javascript">
var answer = 15; // this is the answer to the math question
var attempt; // the user's attempt will be stored in this variable
function guess(){
 attempt = document.getElementById('attempt').value;
 attempt = parseInt(attempt); // this will now treat the textbox input value as an integer
 var result = document.getElementById('result');
 if (attempt == answer){
 result.innerHTML = "Correct!";
 result.innerHTML = "Try again.";
 <p>What is the answer to 10+5?</p>
 Enter your answer:<input type="text" id="attempt"/><br/>
 <input type="button" value="Submit" onclick="guess();"/>
 <p id="result">Enter your answer in the textbox above. It must be a number only.</p>

 Next tutorial: Submitting forms