Click to See Complete Forum and Search --> : JAVASCRIPT : use of addition operator


akrashdi
08-24-2003, 01:39 AM
Hi guys !

I'm new to JavaScript.

I wrote following code but confused about it.

---- This one works (with multiply operator)
document.myform.totalamount.value = document.myform.parking.value * document.myform.tolls.value

---- But this one dosent work (with addition operator)
document.myform.totalamount.value = document.myform.parking.value + document.myform.tolls.value


Can you help me please.

Din

CSW800
08-24-2003, 02:06 AM
Uh, can you elaborate a bit, how doesn't it work? What error do you get?

Charles
08-24-2003, 06:54 AM
Ah, according to my Tarot cards you have misunderstood the additive operator. When applied to strings it concatenates and when applied to numbers it adds them. Form values are strings so you have to cast them as numbers if you want to add.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Example</title>
<style type="text/css">
<!--
label {display:block; margin:1em 0em}
input {display:block}
-->
</style>
<form action="">
<div>
<label>Parking<input type="text" name="parking"></label>
<label>Tolls<input type="text" name="tolls"></label>
<button onclick="this.form.totalAmount.value = Number(this.form.parking.value) + Number(this.form.tolls.value)">Add</button>
<label>Total<input type="text" name="totalAmount"></label>
</div>
</form>