rajju rajju - 3 months ago 16
jQuery Question

Addition of two cells in html table using jQuery

I have written a code. This code takes two inputs from user and adds them and prints them in one cell then takes the same two cells and multiply and prints them in another cell. Here is my code which is working but after this I am trying to take the two results and add them once again this part is not working.

What am I doing wrong?

Here is the code thanks in advance

<HTML>
<HEAD>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function addition(that){
var sum=0;
$("."+that).each(function(){
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
return(sum);
}
function multiply(that){
var prdt=1;
$("."+that).each(function(){
if(!isNaN(this.value) && this.value.length!=0) {
prdt *= parseFloat(this.value);
}
});
return(prdt);
}
</script>
</HEAD>
<BODY>
<table border='1'>
<tr>
<td><input class="a" id="c" type="number" name="quantity" min="0" max="99999999999" required/></td>
<td><input class="a" id="b" type="number" name="quantity" min="0" max="99999999999" required/></td>
<td class="z" id="sum">0</td>
<td class="z" id="mul"></td>
<td id="result"></td>
</tr>
<script>
$(document).ready(function(){
$(".a").each(function(){
$(this).keyup(function(){
x=addition($(this).attr("class"));
$("#sum").html(x);

});
});

$(".a").each(function(){
$(this).keyup(function(){
x=multiply($(this).attr("class"));
$("#mul").html(x);

});
});

$("td.z").each(function(){
$(this).keyup(function(){
x=addition($(this).attr("class"));
$("#result").html(x);

});
});


});


</script>
</table>
</BODY>
</html>

Answer

I took a part of your code and changed it a little. Actually, I used the "setInterval" function to feed the #result with the sum of the two previous fields... Have a look:

<script>
$(document).ready(function(){
$(".a").each(function(){
$(this).keyup(function(){
x=addition($(this).attr("class"));
$("#sum").html(x);

});
});

$(".a").each(function(){
$(this).keyup(function(){
x=multiply($(this).attr("class"));
$("#mul").html(x);

});
});

//    $("td.z").each(function(){
//    $(this).keyup(function(){
//    x=addition($(this).attr("class"));
//    $("#result").html(x);

setInterval(function() {
var z = parseFloat($("#sum").text())+ parseFloat($("#mul").text());
if(!isNaN(z)) {
    $("#result").text(z);
}
}, 500);

});
});


});


</script>

FIDDLE HERE: http://jsfiddle.net/1rcuqskj/1/

Hope this works for you!