Doing arithmetic on user-entered data: parseFloat

See more about:

Try this:

First number

Second number

Sum:

Here’s what I got just now:

Error

Figure 1. Error

Hmm. 5 + 3 = 53?

Here’s the code that causes the trouble:

var number1 = $("#number1").val();
var number2 = $("#number2").val();
var sum = number1 + number2;
$("#sum").text(sum);

Figure 2. The bad code

Variables are both text and numeric in JavaScript. This line:

   var x = "dog";

makes a text variable, also called a string. This line:

   var y = 5;

creates a numeric variable. This line:

   var z = "3";

creates a text variable, that has the text “3” in it. The quotes tell JavaScript to treat the data as text.

Here’s a line from Figure 2:

   var number1 = $("#number1").val();

The val function pulls data the user typed into an input field. It always returns text data, no matter what the user typed into the field. So number1 is always a text variable.

Here’s the code again:

var number1 = $("#number1").val();
var number2 = $("#number2").val();
var sum = number1 + number2;
$("#sum").text(sum);

Figure 2 (again). The bad code

By line 3, the browser has two text variables, number1 and number2.

Then the browser executes this:

   var sum = number1 + number2;

The operator “+” has two meanings in JavaScript:

  • Append – attach one string to another.
  • Add – add two numbers.


Be an author

Want to write your own CoreDogish textbook? Check out FlippedTextbook.Com.

How to...

Lessons

User login


Dogs