Javascript Textbox Update On Simple Addition
I have four texboxes with ids #a #b #c #d. Suppose user enters the values for any three of the above boxes then the remaining textbox will show the sum of values entered in three b
Solution 1:
Make the following changes in your code.
- Check the uppercase
F
inFunction check()
. It needs to be in lowercasef
(i.e)function check()
. - Check the
null
condition like this.if (a && b && c)
- Put separate method for getting the updated
a
,b
,c
andd
values and call that method in yourcheck
method.
Code snippets:
var a, b, c, d;
functionvalues() {
a = Number($('#a').val());
b = Number($('#b').val());
c = Number($('#c').val());
d = Number($('#d').val());
}
functioncheck() {
values();
if (a && b && c) {
var sum1 = a + b + c;
$('#d').val(sum1);
} elseif (a && b && d) {
var sum2 = a + b + d;
$('#c').val(sum2);
} elseif (a && c && d) {
var sum3 = a + c + d;
$('#b').val(sum3);
} elseif (b && c && d) {
var sum4 = b + c + d;
$('#a').val(sum4);
}
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script><inputtype="Number"id="a"onkeyup="check();" /><inputtype="Number"id="b"onkeyup="check();" /><inputtype="Number"id="c"onkeyup="check();" /><inputtype="Number"id="d"onkeyup="check();" />
Solution 2:
Maybe something like this? If you're using jQuery:
$("#b").keyup(function(){
// Add a + b to totalvar a = parseInt($("#a").val());
var b = parseInt($("#b").val());
$("#total").text(a+b);
});
$("#c").keyup(function(){
// Add a + b to totalvar a = parseInt($("#a").val());
var b = parseInt($("#b").val());
var c = parseInt($("#c").val());
$("#d").val(a+b);
});
Edit: this just is a quick draft to give you an idea, not sure if it will work instantly.
Solution 3:
HTML:
<inputtype="Number"id="a" >
<inputtype="Number"id="b" >
<inputtype="Number"id="c">
<inputtype="Number"id="d" >
JS:
$(document).ready(function() {
$( 'input').keyup(function() {
var a=Number($('#a').val());
var b=Number($('#b').val());
var c=Number($('#c').val());
var d=Number($('#d').val());
if (a!=null && b!=null && c!=null)
{
var sum1=a+b+c;
$('#d').val(sum1);
}
elseif (a!=null && b!=null && d!=null)
{
var sum2=a+b+d;
$('#c').val(sum2);
}
elseif (a!=null && c!=null && d!=null)
{
var sum3=a+c+d;
$('#b').val(sum3);
}
elseif (b!=null && c!=null && d!=null)
{
var sum4=b+c+d;
$('#a').val(sum4);
}
});
});
Fiddle: http://jsfiddle.net/1c4pvamm/6/
Solution 4:
Challenge accepted!
A solution in VanillaJS. Works with different number of boxes.
4 Boxes
// Example with 4 boxes
http://jsfiddle.net/wpLdmxeh/2/
5 Boxes
// Example with 5 boxes
Post a Comment for "Javascript Textbox Update On Simple Addition"