...

View Full Version : Javascript numbers help



adrianmcg
07-13-2012, 12: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:
JavaScript:

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

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

var total=no1+no2;

alert (total)
}

HTML
<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

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

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

Philip M
07-13-2012, 01: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.

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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum