Add Two Textbox Values And Display The Sum In A Third Textbox Automatically
I have assigned a task to add two textbox values.I want the result of addition to appear in the 3rd textbox,as soon as enter the values in the first two textboxes,without pressing
Solution 1:
try this
functionsum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
Solution 2:
Try this: Open given fiddle in CHROME
functionsum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
HTML
<inputtype="text"id="txt1" onkeyup="sum();" />
<inputtype="text"id="txt2" onkeyup="sum();" />
<inputtype="text"id="txt3" />
Solution 3:
i didn't find who made elegant answer , that's why let me say :
Array.from(
document.querySelectorAll('#txt1,#txt2')
).map(e =>parseInt(e.value) || 0) // to avoid NaN
.reduce((a, b) => a+b, 0)
window.sum= () =>document.getElementById('result').innerHTML=
Array.from(
document.querySelectorAll('#txt1,#txt2')
).map(e=>parseInt(e.value)||0)
.reduce((a,b)=>a+b,0)
<inputtype="text"id="txt1"onkeyup="sum()"/><inputtype="text"id="txt2"onkeyup="sum()"style="margin-right:10px;"/><spanid="result"></span>
Solution 4:
Well, base on your code, you would put onkeyup=sum() in each text box txt1 and txt2
Solution 5:
well I think the problem solved this below code works:
functionsum() {
var result=0;
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
if (txtFirstNumberValue !="" && txtSecondNumberValue ==""){
result = parseInt(txtFirstNumberValue);
}elseif(txtFirstNumberValue == "" && txtSecondNumberValue != ""){
result= parseInt(txtSecondNumberValue);
}elseif (txtSecondNumberValue != "" && txtFirstNumberValue != ""){
result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
}
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
Post a Comment for "Add Two Textbox Values And Display The Sum In A Third Textbox Automatically"