This script getting concatenation. Not adding.

Posted by maninaanee-8287 under JavaScript on 1/30/2012 | Points: 10 | Views : 1777 | Status : [Member] | Replies : 4
Hi, i want to add two textboxes, it's getting concatenation. It's not adding yaar. what to do.
<SCRIPT language = JavaScript>

function calculate() {
A = document.frmOne.txtFirstNumber.value
B = document.frmOne.txtSecondNumber.value
C = (A + B)
document.frmOne.txtThirdNumber.value = C
}

</SCRIPT>


</head>
<body>
<FORM NAME = frmOne>

Number One: <INPUT TYPE = Text NAME = txtFirstNumber SIZE = 5 value ="">

Number Two: <INPUT TYPE = Text NAME = txtSecondNumber SIZE = 5 value ="">
<P>
Total: <INPUT TYPE = Text NAME = txtThirdNumber SIZE = 5 value = "">
<P>
<Input Type = Button NAME = b1 VALUE = "Add Numbers" onClick = calculate()>

</FORM>




Responses

Posted by: Sksamantaray on: 1/30/2012 [Member] Silver | Points: 25

Up
0
Down
why dont you convert the textbox value to int first, before adding?

Thanks,
Sanjay

maninaanee-8287, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sksamantaray on: 1/30/2012 [Member] Silver | Points: 25

Up
0
Down
Try This


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<SCRIPT language = "JavaScript">

function calculate() {
A = parseInt(document.form1.txtFirstNumber.value);
B = parseInt(document.form1.txtSecondNumber.value);
C = (A + B)
document.form1.txtThirdNumber.value = C
}

</SCRIPT>
</head>
<body>
<form id="form1" runat="server">
<div>
Number One: <INPUT TYPE = Text NAME = txtFirstNumber SIZE = 5 value ="">

Number Two: <INPUT TYPE = Text NAME = txtSecondNumber SIZE = 5 value ="">
<P>
Total: <INPUT TYPE = Text NAME = txtThirdNumber SIZE = 5 value = "">
<P>
<Input Type = Button NAME = b1 VALUE = "Add Numbers" onClick = calculate()>

</div>
</form>
</body>
</html>


Thanks,
Sanjay

maninaanee-8287, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Blessyjees on: 1/30/2012 [Member] Bronze | Points: 25

Up
0
Down
Hi,

If you add + sign between two values without conversion, it acts as a string concatenation. So you need to convert this as int for performing mathematical operation.

Blessy Baby
Digitalmesh Softech pvt Ltd
https://blessybaby.wordpress.com/

maninaanee-8287, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajni.Shekhar on: 3/20/2012 [Member] Bronze | Points: 25

Up
0
Down
check this code. parse value into integer using parseInt

<SCRIPT language = JavaScript>

function calculate() {
A = document.frmOne.txtFirstNumber.value
B = document.frmOne.txtSecondNumber.value
C = (parseInt(A) + parseInt(B))
document.frmOne.txtThirdNumber.value = C
}

</SCRIPT>


Thanks,
Rajni Shekhar

maninaanee-8287, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response