View Full Version : Javascript numbers help

07-13-2012, 01:46 PM
Hi I am new to learning Javascript. I want an alert to add two numbers from 2 text boxes together. What i get is 1 + 2 = 12.

Here is my code:

function sum(){
var no1 =document.getElementById('no1').value;

var no2 =document.getElementById('no2').value;

var total=no1+no2;

alert (total)

<p>Number 1 <input type="text" id="no1"></p>

<p>Number 2 <input type="text" id="no2">
<input type="button" value="add" onclick="sum()"></p>

Please help

07-13-2012, 02:34 PM
In JavaScript, "+" is concatenation unless you specify otherwise.

var total = parseFloat(no1) + parseFloat(no2);

Philip M
07-13-2012, 02:54 PM
var no1 =document.getElementById('no1').value;

Do not use the same name for a Javascript variable and an HTML element. It will in fact work here, but is very dangerous.

All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

07-13-2012, 04:00 PM
Och.. I was in a hurry and forgot the string delimiters! Tnx, Philip.