How will i able to add this two numbers using javascript - javascript

I have two number that calculates the amount and vat amount using JavaScript. Now how will I be able to do this?
<tr>
<th>Amount: </th>
<td><input id="amount" type="text" name="amount" class="form-control" required />
</td>
</tr>
<tr>
<th>VAT 20% Amt: </th>
<td>
<input id="vatAmt" type="text" name="vatAmount" class="form-control" />
</td>
</tr>
<tr>
<th>Total Amount: </th>
<td>
<span id="totalAmount"></span>
</td>
</tr>
then the amount due
<div class="col-md-6" >
<h3>Amount Due: £ <span id="amountValue"></span></h3>
</div>
My JavaScript code is below:
$("#amount").keyup(function () {
var value = $(this).val();
$("#amountValue").text(value);
});
$("#vatAmt").keyup(function () {
var valueVat = $(this).val();
var sum = value + valueVat;
$("#totalAmount").text(sum);
}).keyup();
Can someone help me figured this thing out? Any help is muchly appreciated. TIA

value isn't defined in your second keyup handler. You need to define it:
$("#vatAmt").keyup(function () {
var value = $("#amount").val(); // <--- here
var valueVat = $(this).val();
var sum = value + valueVat;
$("#totalAmount").text(sum);
}).keyup();
When you define a variable inside a function, it's only available within that function. Another option could be to define it globally, but I generally prefer keeping scope limited to only where you need it. Within your keyup handler for #varAmt you need two values, so you would have two calls to .val() to get two values.
Note: It's possible you may also want to use parseInt or something similar to perform your addition:
$("#vatAmt").keyup(function () {
var value = parseInt($("#amount").val()); // <--- here
var valueVat = parseInt($(this).val()); // <--- and here
var sum = value + valueVat;
$("#totalAmount").text(sum);
}).keyup();
JavaScript is pretty forgiving about types, but sometimes bugs can creep in if you rely on that. And .val() returns a string because the input is text, even if that text happens to be numeric characters.

This will do
<tr>
<th>Amount: </th>
<td><input id="amount" type="number" name="amount" class="form-control" required />
</td>
</tr>
<tr>
<th>VAT 20% Amt: </th>
<td>
<input id="vatAmt" type="number" name="vatAmount" class="form-control" />
</td>
</tr>
<tr>
<th>Total Amount: </th>
<td>
<span id="totalAmount"></span>
</td>
</tr>
<div class="col-md-6">
<h3>Amount Due: £ <span id="amountValue"></span></h3>
</div>
var value;
$("#amount").keyup(function() {
value = $(this).val();
$("#amountValue").text(value);
})
$("#vatAmt").keyup(function() {
var valueVat = $(this).val();
var sum = Number(value) + Number(valueVat);
$("#totalAmount").text(sum);
}).keyup();

Related

How to set min and max on an input type accepting floating value?

There are plenty of examples showing how to set min and max with integers. I need to ensure the range of values can even be float. Below is how I'm setting the attributes value and max for the input type refund_amount. The problem here is that one can enter a value higher than max value set with Jquery.
window.onload = function() {
var src = document.getElementById("grand_total");
var dst = document.getElementById("refund_amount");
if (dst != "") {
dst.setAttribute("value", src.textContent);
dst.setAttribute("max", src.textContent);
}
};
HTML:
<tr>
<td align="right" colspan="3">Enter Refund Amount</td>
<td align="left" colspan="4"><input type="text" size="11" id="refund_amount"
name="refund_amount" value='' min="" max="" required/></td>
</tr>
How do I ensure it never allows higher value than what max attribute holds?
The min and max attributes only work on type="number" inputs. It's also worth noting that they are not reliable as a means of validation, as they do not prevent the user from typing in a number outside the bounds of the min/max settings.
To work around that you can manually validate the value and correct it to be within bounds by using a change event and the Math.min() and Math.max() functions. Try this:
window.addEventListener('load', function() {
var src = document.getElementById("grand_total");
var dst = document.getElementById("refund_amount");
if (dst) {
dst.value = dst.max = src.textContent;
}
});
document.querySelectorAll('input[type="number"]').forEach(input => {
input.addEventListener('change', e => {
let el = e.target;
el.value = Math.min(Math.max(el.value, el.min), el.max);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Grand total</td>
<td id="grand_total">25.68</td>
</tr>
<tr>
<td align="right" colspan="3">Enter Refund Amount</td>
<td align="left" colspan="4">
<input type="number" step="1" min="11.11" id="refund_amount" name="refund_amount" value="" required />
</td>
</tr>
</table>

How to get values to the outside from three functions and update them in real time?

I have a table which lets users to add number of participants for an event. in it I used input type number field to get number of participants. then I calculate how much fee they have to pay for each passenger type. I have 3 passenger types.
My table looks like this,
I use keyup mouseup bind to get the input value by user and multiplied it with fee for one participant.
var totalAdults;
jQuery("#number_adults").bind('keyup mouseup', function () {
var numOfAdults = jQuery("#number_adults").val();
totalAdults = numOfAdults * adultFee;
});
I have 3 of above functions to calculate and real time display how much fee that they have to pay in each passenger type.
Now I need to get the total sum of all three passenger type fees and display/update it in real time to the user, at the end of my table.
I tried making each passenger type total value global and calculating it's sum, but I get an error saying missing semicolon error linked to this MDN article
I'm stuck here. how can I get total value on all three passenger types outside their respective functions and display that value correctly in real time? (when they update number of passengers, total for passenger type is changing, I need to change final total accordingly). please help
Update:
this is the html table that I used. this get repeated another two times for other two passenger types.
var adultFee = 150;
var finalTotal = 0;
jQuery("#number_adults").bind('keyup mouseup', function() {
var numOfAdults = jQuery("#number_adults").val();
totalAdults = numOfAdults * adultFee;
jQuery("#adult_amount").html(totalAdults);
// console.log(totalAdults);
finalTotal = finalTotal + totalAdults;
console.log(finalTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td style="font-weight: 600;">Adult</td>
<td id="adult_price" name="adult_price">150.00</td>
<td>
<input id="number_adults" max="3" min="1" name="number_adults" type="number" value="0" class="form-control">
</td>
<td name="amount">
<p id="adult_amount"></p>
</td>
</tr>
This is how I tried to get the final total, it doesn't display any result
jQuery(document).on('change', '#adult_amount', function() {
finalTotal = finalTotal+totalAdults;
alert(finalTotal);
});
I made a working example for you.
$('.inputs').each(function(){
$(this).on('change keyup', function(){
let sumTotal = 0;
$('.inputs').each(function(){
sumTotal += $(this).val() * +$(this).parent().next().data('price');
});
$('.total').text(`${sumTotal} $`);
});
});
td:nth-child(3),
th:nth-child(3){
text-align:center;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th>QTY</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Child</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="150">150 $</td>
</tr>
<tr>
<td>Adult</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="200">200 $</td>
</tr>
<tr>
<td>Adult Plus</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="250">250 $</td>
</tr>
<tr>
<td>Total - </td>
<td></td>
<td class="total">0.00 $</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
(https://codepen.io/bichiko/pen/JQWomy)
Here is a solution which should do what you need.
Compared to your code, the key changes are:
Use classes instead of IDs to identify the elements within each row. This means you can handle changes to all your fields using the same event handling code. I've given all your quantity fields the .qty class, and then bound the event to that class, so all elements with that class will run the same function.
Within the function, I've stripped out all direct references to fields - instead, to get the price field, and the total field for the relevant type, the code uses the positions of the fields relative to each other in the page, it uses the .parent(), .next(), and .prev() functions to find the total and amount fields which are within the same table row as the altered quantity field (which will always be this inside the event handler), so that it does the calculations on the right fields.
To calculate the final overall total, I've defined a separate function. Again this uses a class selector to identify all the "amount" fields, and add each of those values together to get the total. Since this function is triggered at the end of the event handler, it will always update the grand total whenever one of the quantities is updated.
Other minor changes:
use .on() instead of the deprecated .bind()
jQuery(".qty").on('keyup mouseup', function() {
var tdElement = jQuery(this).parent();
var qty = parseInt(this.value);
var fee = parseFloat(tdElement.prev(".price").text());
var typeTotal = qty * fee;
tdElement.next(".amount").html(typeTotal);
calcFinalTotal();
});
function calcFinalTotal()
{
var finalTotal = 0;
$(".amount").each(function() {
finalTotal += parseFloat($(this).text());
});
$("#total").text(finalTotal);
}
td, th
{
border: solid 1px #cccccc;
padding: 5px;
text-align:left;
}
table {
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Passenger Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<tr>
<th>Adult</th>
<td class="price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th>Type 2</th>
<td class="price" id="type3_price">200.00</td>
<td>
<input max="3" min="1" name="number_type" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th>Type 3</th>
<td class="price" id="type3_price">200.00</td>
<td>
<input max="3" min="1" name="number_type" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th colspan="3">Grand Total</th>
<td id="total"></td>
</tr>
</table>
You can simply loop on every rows on the table and calculate the total sum and also the individual. Here i done by the dynamic method. if the total of each passenger is inserted in a unique input, then you can access from that input. Otherwise please follow the method
$(document).on('keyup mouseup','.qty', function() {
calculate();
});
function calculate(){
var finalTotal = 0;
var old = 0;
var mature = 0;
var adult = 0;
$('.qty').each(function(key,value){
$qty = $(this).val();
$type = $(this).attr('data-type');
$amount = $(this).parent().siblings('.adult_price').html();
$total = Number($qty) * parseFloat($amount);
$(this).parent().siblings('.amount').html($total);
finalTotal += $total;
if($type == 'adult')
adult += parseFloat($total);
else if($type == 'mature')
mature += parseFloat($total);
else if($type == 'old')
old += parseFloat($total);
});
$('.grandTotal').html(finalTotal);
// console.log('Adult',adult);
// console.log('Mature',mature);
// console.log('Old',old);
}
table {
border-collapse: collapse;
width: 80%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Passenger Types</th>
<th>Amount</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><b>Adult</b></td>
<td class="adult_price" name="adult_price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="adult">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td><b>Mature</b></td>
<td class="adult_price" name="adult_price">200.50</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="mature">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td><b>Old</b></td>
<td class="adult_price" name="adult_price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="old">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td colspan="3"><b>Grand Total</b></td>
<td class='grandTotal'>100</td>
</tr>
</tbody>
</table>
jQuery is very flexible use class instead of id. If you use inputs, selects, etc you should delegate the input or change event to them.
$('input').on('input', function() {...
input event will trigger as soon as user types or selects on or to an input tag. change event will trigger when a user types or selects on or to an input and then clicks (unfocus or blur event) elsewhere.
The HTML is slightly modified for consistency. Note that there are 2 extra inputs per <tr>.
When using input inside tables you can traverse the DOM by first referencing the imputed/changed/clicked tag as $(this) then climb up to the parent <td> and from there either go to the next <td> using .next() or go to the previous <td> using .prev(). Once you get to a neighboring <td> use .find() to get the input within. When extracting a number from an input it is normally a string but with jQuery method .val() it should extract input value as a number automatically. Details commented in demo.
/*
//A - Any tag with the class of .qty that the user inputs data into triggers a function
//B - Get the value of the imputed .qty (ie $(this))
//C - reference $(this) parent <td> go to the next <td> then find a tag with the class .price and get its value
//D - reference $(this) parent <td> go to the previous <td> then find a tag with the class of .total then set its value to the product of qty and price and fix it with hundredths (.00 suffix)
//E - Declare an empty array
//F - Get the value of each .total, convert it into a number then push the number into the empty array
//G - Use .reduce() to get the sum of all values within the array then fix it with hundredths (.00 suffix) and set it as the value of .grand
*/
$('.qty').on('input', function() { //A
var qty = $(this).val(); //B
var price = $(this).parent().prev('td').find('.price').val(); //C
$(this).parent().next('td').find('.total').val((qty * price).toFixed(2)); //D
var totals = []; //E
$('.total').each(function() {
totals.push(Number($(this).val()));
}); //F
$('.grand').val(totals.reduce((sum, cur) => sum + cur).toFixed(2)); //G
});
table {
table-layout: fixed;
}
td {
width: 6ch
}
[readonly] {
border: 0;
width: 6ch;
text-align: right
}
[type=number] {
text-align: right
}
<table>
<tr>
<td style="font-weight: 600;">Adult</td>
<td><input class="price" name='price' value='150.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0" class="form-control">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td style="font-weight: 600;">Senior</td>
<td><input class="price" name='price' value='100.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0" class="form-control">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td style="font-weight: 600;">Child</td>
<td><input class="price" name='price' value='75.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td colspan='3' style='text-align:right;'>Total</td>
<td><input class='grand' name='grand' value='0' readonly></td>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is axample of yours problem, try using object
var data = {a:0, b:0, c: 0}
function one (){
data.a = data.a + 10
console.log(data.a)
total()
}
function two (){
data.b = data.b + 10
total()
console.log(data.b)
}
function three () {
data.c = data.c + 30
total()
console.log(data.c)
}
function total () {
var totaly = data.a + data.b + data.c
console.log('Total input :', totaly)
}
<button onclick="one()"> get A </button>
<button onclick="two()"> get B</button>
<button onclick="three()"> get C </button>

onChange event for calculation in dynamic grid updates wrong rows - Classic asp

I have an old ASP site that needs a change. I need a basic grid to set pricing.
I want to enter a price in one column and have it display text of "Debit" or "Credit" in another column based on positive or negative input. I also want to calculate the extended price based on qty. I've just started with the first (text display) one for now, and can't get it to work.
The grid could have n number of rows based on the data set returned so I have a counter which I concatenate to the input IDs to indicate the row number. The counter is working fine and I can see the id's increment correctly. I've tried to pass the correct input value and id but when the function fires it updates the wrong rows. Actually it updates all the rows below the row I've changed. I have spent WAY too much time banging my head on what I thought would be a 15 min issue. Need a few more pairs of eyes.
<script>
function myFunction(val) {
data_length = document.getElementById("datalength").value;
i = 0;
while(i++ < data_length)
if (val > 0) {
document.getElementById("chargepay" +i).innerHTML = "Credit";
}
else
{
document.getElementById("chargepay" +i).innerHTML = "Debit";
}
}
</script>
Here is the row in the grid loop that has the input field to pass the amount value:
<td align="center"><input id="AMNT<%=count%>" size="10" name="AMNT"
onchange="myFunction(this.value)"/></td>
Here is the row in the grid to display the update from the onchange
<td align="center"><p id="chargepay<%=count%>"</p>td>
When I update the value in the input box in first row, it updates all rows below but not that row. I have a loop, I think. I only want it to update one row at a time as I change the values.
Any help / direction would be appreciated.
If you haven't included you need to include the JQuery library from local system or CDN.
https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
You need to add the change even for every input involved in your mathematical calculation. Here 'this; is passed as argument, so that we can find the parent row(through which all other controls contained in it can be searched.
onchange="myFunction(this)"
Inside the function 'myFunction', We at first finds the closest/parent 'tr'.
Again we selects the input field corresponding to Quantity, Amount etc(you can add more if required). The selection can be based on Id, Name, Class etc
var qty = currentRow.find('input[name=QTY]').val();
//or (id starting with 'QTY')
var qty = currentRow.find('input[id*=QTY]').val();
//or (give any class name and replace it instead of 'class-name')
var qty = currentRow.find('input.class-name').val();
We need to convert the string value to float to perform accurate mathematical calculations. While parsing empty string we may end up with 'NAN' - Not a Number. So we need to check before parsing.
qty = (qty == "" ? 0 : parseFloat(qty));
After all this you can use this value for any math calculation and setting it as text of the tag or any other.
If its p, div, span you need to set it as 'text'
currentRow.find('input[name=TOT]').text(totalAmount);
And if its input you need to set it as 'value'
currentRow.find('p[name=TOT]').val(totalAmount);
function myFunction(elem) {
var currentRow = $(elem).closest('tr');
var qty = currentRow.find('input[name=QTY]').val();
var amt = currentRow.find('input[name=AMNT]').val();
qty = (qty == "" ? 0 : parseFloat(qty));
amt = (amt == "" ? 0 : parseFloat(amt));
var totalAmount = qty * amt;
currentRow.find('p[name=TOT]').text(totalAmount);
currentRow.find('p[name=TYPE]').text(totalAmount > 0 ? 'Credit' : 'Debit');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td align="center">
<input id="QTY1" size="10" name="QTY" onchange="myFunction(this)" />
</td>
<td align="center">
<input id="AMNT1" size="10" name="AMNT" onchange="myFunction(this)" />
</td>
<td align="center">
<p id="TOT1" name="TOT"></p>
</td>
<td align="center">
<p id="chargepay1" name="TYPE"></p>
</td>
</tr>
<tr>
<td align="center">
<input id="QTY2" size="10" name="QTY" onchange="myFunction(this)" />
</td>
<td align="center">
<input id="AMNT2" size="10" name="AMNT" onchange="myFunction(this)" />
</td>
<td align="center">
<p id="TOT2" name="TOT"></p>
</td>
<td align="center">
<p id="chargepay2" name="TYPE"></p>
</td>
</tr>
<tr>
<td align="center">
<input id="QTY3" size="10" name="QTY" onchange="myFunction(this)" />
</td>
<td align="center">
<input id="AMNT3" size="10" name="AMNT" onchange="myFunction(this)" />
</td>
<td align="center">
<p id="TOT3" name="TOT"></p>
</td>
<td align="center">
<p id="chargepay3" name="TYPE"></p>
</td>
</tr>
</table>

Custom validation plugin fails with multiple table rows

Trying to self create a validation that compares Gross and Tare values in the table using jQuery validation plugin. Tare should always be smaller than Gross.
Here is the JS code:
$.validator.addMethod('lessThan', function (value, element, param) {
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(param).val());
return i <= j;
}, "Tare must less than Gross");
$('#myForm').validate({rules: {tare: {lessThan: ".gross"}}});
And my HTML:
<form id="myForm">
<table id="lineItemTable">
<thead>
<th>
<tr>
<td>Gross</td>
<td>Tare</td>
</tr>
</th>
</thead>
<tbody>
<tr>
<td><input type="text" name='gross' class="gross"/></td>
<td><input type="text" name='tare' class="tare"/></td>
</tr>
<tr>
<td><input type="text" name='gross' class="gross"/></td>
<td><input type="text" name='tare' class="tare"/></td>
</tr>
</tbody>
</table>
</form>
This code works fine when only have one row involved.
When comes two table rows, it compares the 2nd row tare value with the 1st row gross value. Apparently I want it to compare 2nd row tare value with 2nd row gross value. Also for some reason the error message shows up at the 1st row.
Here is one screen shot:
Please advise how do I change my code to make it working properly.
And here is the CDN that I am using:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
Looking for $('.gross').val() will always retrieve the value of the first matched element (in the whole document).
Instead, look only in the row containing the element being validated:
var j = parseInt($(element).closest('tr').find(param).val());
$.validator.addMethod('lessThan', function(value, element, param) {
console.log(element);
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(element).closest('tr').find(param).val());
return i <= j;
}, "Tare must less than Gross");
$('#myForm').validate({
rules: {
tare: {
lessThan: ".gross"
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="myForm">
<table id="lineItemTable">
<thead>
<th>
<tr>
<td>Gross</td>
<td>Tare</td>
</tr>
</th>
</thead>
<tbody>
<tr>
<td>
<input type="text" name='gross' class="gross" />
</td>
<td>
<input type="text" name='tare' class="tare" />
</td>
</tr>
<tr>
<td>
<input type="text" name='gross' class="gross" />
</td>
<td>
<input type="text" name='tare' class="tare" />
</td>
</tr>
</tbody>
</table>
</form>

How to use operations based on the number of user inputs?

I am trying to make a simple calculator which tells students their average university mark based on their grades.
JSFiddle
I'm trying to get the formula to do this:
Step 1: (Mark * Credit Point)
Step 2: Add these totals together
Step 3: Get this total and divide it by the number of user inputs.
Having trouble with steps 2 and 3.
Right now when calculate is clicked, it just appends the single answer of each row one after the other. I want to add these values then divide it by the number of inputs.(As the amount of subjects will vary between users)
Any help is really appreciated.
HTML:
<div>
<table class='table'>
<tr>
<th> Unit Code </th>
<th> Mark </th>
<th> Credit Point </th>
</tr>
<tr>
<td> <input type="text"></td>
<td> <input type="text" class='mark'> </td>
<td> <input type="text" class='creditPoint'> </td>
</tr>
<tr>
<td> <input type="text"></td>
<td> <input type="text" class='mark'> </td>
<td> <input type="text" class='creditPoint'> </td>
</tr>
<tr>
<td> <input type="text"></td>
<td> <input type="text" class='mark'></td>
<td> <input type="text" class='creditPoint'> </td>
</tr>
</table>
</div>
Javascript:
$('#wam').click(function() {
$('.table tr').each(function() {
var mark = $(this).find('input.mark').val();
var cp = $(this).find('input.creditPoint').val();
var total = ((mark * cp));
// Find the total then divide by the number of entries
$('body').append(total);
});
});
You need to use a shared variable in the loop
$('#wam').click(function () {
var total = 0,
count = 0;
$('input.mark').each(function () {
var mark = this.value;
var cp = $(this).parent().next().find('input.creditPoint').val();
var t = mark * cp || 0;//if both the fields are not entered don't add them
if (t) {
//if the product is 0 then don't count the value
count++;
}
total += t;
});
$('#total').text(total);
$('#total2').text(count ? total / count : 0);//the ternary condition to prevent division by 0
});
Demo: Fiddle

Categories

Resources