i have two text boxes with the id as first and second respectively.In javascript i took the values using

var first=document.getElementbyId("first").value.
var second=document.getElementbyId("second").value.
var sum=first+second;

But the problem is when i alert the sum i got the result as concatenated.i didn't get the original sum.I also tried it as first=Number(first) , but there is no result.

can u help me?
thanx in advance

var1=document.getelementbyid('txt1').value
var2=document.getelementbyid('txt2').value
var3=Number(var1)+Number(var2)

or concentrate on eval() function in javascript by googling....

commented: Ah! Didn't know that.. +7

You should use parseInt.

var1=document.getelementbyid('txt1').value;
var2=document.getelementbyid('txt2').value;
var3=parseInt(var1)+parseInt(var2);
alert(var3);
...
var3 = parseFloat(var1)+parseFloat(var2);
alert(var3);

Will do also fine. This additionally ensures that values like: 1.356 + 6.32 don't get rounded into a sum of say 7, so you get the correct value of 7.676 ...

Regards @all

> concentrate on eval() function in javascript by googling

As in concentrate on swatting a fly with a hammer? eval sort of fires off a mini-compiler which dynamically evaluates the string passed to it. Look for better ways of doing things and use eval only when required. E.g. when evaluating a random expression entered by the user when creating a calculator application in Javascript.

> You should use parseInt .

Surprise surprise!

parseInt("09") + parseInt("09")

Moral: Always specify the base when using parseInt .

> This additionally ensures that values like: 1.356 + 6.32 don't get rounded into a sum of
> say 7, so you get the correct value of 7.676

I would still stay away from all those parseXXX variations since they give results which you least expect.

alert(parseFloat("1asldfjas"));
alert(Number("1asdfsdf"));

The question was, I believe, "how to make sure he is summing numbers instead of symbols of their presentation?". alert(parseFloat("1asldfjas")); will yield a number as expected. In this case: 1; [but no other order will!] the opposite will return NaN [not a number] thing.

Although, your reply was rich and informative till this point, I'd still like to know what was your suggested solution to this problem?

Regards.

p.s.:
I'm totally aware that validating input before anything else is always the safest way to go.

My suggested solution was to use the Number constructor so as to perform addition as well as validation in a single go. But some additional validation will always be required to prevent inputs like 1E2 creeping through and giving unexpected results.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.