How to auto calculate table rows using jquery? - javascript

I have a table with 3 table rows, each row contains 5 columns with input text boxes, the last column is for the total of the values inputted in the 4 columns. I want to calculate the total automatically using jquery or javascript after the 4 columns was filled with values. How could I do this? Here is my table code.
Table
<table name="tbl_a" id="tbl_a">
<tr>
<td><span style="margin-left:30px;">a. Provision of certified seeds</span></td>
<td>no. of bags</td>
<td>per AT</td>
<td><input type="text" class="form-control" name="at[a]" id="a" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[b]" id="b" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[c]" id="c" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[d]" id="d" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[total_1]" id="total_1" value="" placeholder="total" style= "width:160px;"/></td>
</tr>
<tr>
<td></td>
<td>no. of farmers</td>
<td></td>
<td><input type="text" class="form-control" name="at[e]" id="e" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[f]" id="f" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[g]" id="g" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[h]" id="h" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[total_2]" id="total_2" value="" value="" placeholder="total" style= "width:160px;"/></td>
</tr>
<tr>
<td style="text-align:center;">Rehab Seeds</td>
<td>no. of bags</td>
<td>per AT</td>
<td><input type="text" class="form-control" name="at[i]" id="i" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[j]" id="j" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[k]" id="k" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[l]" id="l" value="" style= "width:160px;"/></td>
<td><input type="text" class="form-control" name="at[total_3]" id="total_3" value="" value="" placeholder="total" style= "width:160px;"/></td>
</tr>
</table>

First of all please google for what you wanted to achieve, learn yourself, try to find the solution. If you still not succeeded, ask question with the relevant code that you have tried and with some playgrounds such as jsfiddle.net or jsbin.com etc.
However, here is the script which I used. I added total to the last input field.
$(function () {
var tbl = $('#tbl_a');
tbl.find('tr').each(function () {
$(this).find('input[type=text]').bind("keyup", function () {
calculateSum();
});
});
function calculateSum() {
var tbl = $('#tbl_a');
tbl.find('tr').each(function () {
var sum = 0;
$(this).find('input[type=text]').not('.total').each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$(this).find('.total').val(sum.toFixed(2));
});
}
});
Here is the result. In this script, you can have any number of rows, but the last row needed to have a different class name otherwise its value also added to the total.

On input change, calculate inputs's total. If one input is empty return, if not assign total to last input of tr.
$(".form-control").change(function(){
var tr = $(this).parents("tr");
var total = 0;
for (var i = 0; i < tr.find("input").length; i++) {
if ($(tr).find("input").eq(i).val() == 0 || $(tr).find("input").eq(i).val() == "")
return;
total += parseInt($(tr).find("input").eq(i).val());
}
$(tr).find("input").eq($(tr).find("input").length-1).val(total);
}

Related

Display all data in db and use for loop in Javascript

I have a checkbox which will re-enable all input textboxes in a row if checked. The current state is I can only do it on the first row.
This is my code:
#foreach($kucings as $cat)
<tr>
<th scope="row">
<input type="hidden" name="" value="">
<input type="checkbox" id="name" name="name" value="{{$cat->id}}"/>
{{$cat->name}}
</th>
<td><input type="number" id="age" value="" disabled /></td>
<td><input type="number" id="weight" value="" disabled /></td>
<td><input type="number" id="height" value="" disabled /></td>
</tr>
#endforeach
Below is my javascript:
<script>
document.getElementById('name').onchange = function() {
document.getElementById('age').disabled = !this.checked;
document.getElementById('weight').disabled = !this.checked;
document.getElementById('height').disabled = !this.checked;
};
</script>
You cannot have multiple elements with the same id. You can have dynamic id like this and add event listeners for each of them.
#foreach($kucings as $key => $cat)
<tr>
<th scope="row">
<input type="hidden" name="" value="">
<input type="checkbox" id="name-{{$key}}" name="name" value="{{$cat->id}}"/>
{{$cat->name}}
</th>
<td><input type="number" id="age-{{$key}}" value="" disabled /></td>
<td><input type="number" id="weight-{{$key}}" value="" disabled /></td>
<td><input type="number" id="height-{{$key}}" value="" disabled /></td>
</tr>
#endforeach
<script>
let catCount = {{count($kucings)}};
for (let i = 0; i < catCount.length; i++) {
document.getElementById('name-'+i).onchange = function() {
document.getElementById('age-'+i).disabled = !this.checked;
document.getElementById('weight-'+i).disabled = !this.checked;
document.getElementById('height-'+i).disabled = !this.checked;
}
};
</script>

Need help for array field

This script works fine for me:
<script>
calculate = function(){
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value = parseInt(resources)* parseInt(minutes);
}
</script>
<form action="ProvideMedicinProcess.php" class="register" method="POST">
<table id="dataTable" border="1">
<tbody>
<tr>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input type="datetime-local" required="required" name="VisitDate[]"></td>
<td>
<input class="form-control"type="text" required="required" placeholder="Symptoms" name="Symptoms[]">
</td>
<td>
<input class="form-control" type="text" required="required" placeholder="GivenMedicin" name="GivenMedicin[]">
</td>
<td>
<input id="a1" class="form-control" type="text" required="required" placeholder="UnitePrice" name="UnitePrice[]" onblur="calculate()" >
</td>
<td>
<input id="a2" class="form-control" type="text" required="required" placeholder="Quentity" name="Quentity[]" onblur="calculate()" >
</td>
<td>
<input id="a3" class="form-control" type="text" required="required" placeholder="SubTotal" name="SubTotal[]" >
</td>
</tr>
</tbody>
</table>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" />
<input class="submit" type="submit" value="Confirm" />
<input type="hidden" value="<?php echo $PatientIDSearch ?>" name="PatientIDSearch" />
</form>
But I need to calculate All Subtotal
Some issues:
If you add rows, you'll have to avoid that you get duplicate id property values in your HTML. It is probably easiest to just remove them and identify the input elements via their names, which does not have to be unique
It is bad practice to assign to a non-declared variable. Use var, and in the case of functions, you can just use the function calculate() { syntax.
Make the subtotal input elements read-only by adding the readonly attribute, otherwise the user can change the calculated total.
Instead of responding on blur events, you'll get a more responsive effect if you respond to the input event. And I would advise to bind the event handler via JavaScript, not via an HTML attribute.
I would fix some spelling errors in your elements (but maybe they make sense in your native language): Quantity with an 'a', UnitPrice without the 'e'.
You can use querySelectorAll to select elements by a CSS selector, and then Array.from to iterate over them.
See below snippet with 2 rows:
function calculate(){
var unitPrices = document.querySelectorAll('[name=UnitPrice\\[\\]]');
var quantities = document.querySelectorAll('[name=Quantity\\[\\]]');
var subTotals = document.querySelectorAll('[name=SubTotal\\[\\]]');
var grandTotal = 0;
Array.from(subTotals, function (subTotal, i) {
var price = +unitPrices[i].value * +quantities[i].value;
subTotal.value = price;
grandTotal += price;
});
// Maybe you can also display the grandTotal somehwere.
}
document.querySelector('form').addEventListener('input', calculate);
input { max-width: 7em }
<form action="ProvideMedicinProcess.php" class="register" method="POST">
<table id="dataTable" border="1">
<tbody>
<tr>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input type="datetime-local" required="required" name="VisitDate[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Symptoms" name="Symptoms[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Given Medicin" name="GivenMedicin[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Unit Price" name="UnitPrice[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Quantity" name="Quantity[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="SubTotal" readonly name="SubTotal[]" ></td>
</tr>
<tr>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input type="datetime-local" required="required" name="VisitDate[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Symptoms" name="Symptoms[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Given Medicin" name="GivenMedicin[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Unit Price" name="UnitPrice[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Quantity" name="Quantity[]"" ></td>
<td><input class="form-control" type="text" required="required" placeholder="SubTotal" readonly name="SubTotal[]" ></td>
</tr>
</tbody>
</table>
</form>

jQuery- Dynamically multiply input values of table rows with different id

Dynamically adding table rows using below code. User ID is appended for input id.
var selResId = jQuery('#grid').jqGrid('getGridParam', 'selarrrow');
var j=1;
for (var i=0, il=selResId.length; i < il; i++) {
var name = jQuery('#grid').jqGrid('getCell', selResId[i], 'USER_NAME');
$('#addr'+j).html("<td style='text-align:center;'>"+name+"</td><td><input id='hours_"+selResId[i]+"' value='80' type='text' readonly /></td><td><input id='rate_"+selResId[i]+"' type='text' /></td><td><input name='markup_"+selResId[i]+"' type='text'/></td><td><input name='totalcost_"+selResId[i]+"' type='text' readonly></td>");
$('#resource_table').append('<tr id="addr'+(j+1)+'"></tr>');
j++;
}
}
HTML Generated
<tr id="addr1">
<td>John Doe</td>
<td><input type="text" readonly="" value="80" id="hours_10"></td>
<td><input type="text" value="" id="rate_10"></td>
<td><input type="text" value="" id="markup_10"></td>
<td><input type="text" readonly="" value="" id="totalcost_10"></td>
</tr>
<tr id="addr2">
<td>Foo User</td>
<td><input type="text" readonly="" value="80" id="hours_11"></td>
<td><input type="text" value="" id="rate_11"></td>
<td><input type="text" value="" id="markup_11"></td>
<td><input type="text" readonly="" value="" id="totalcost_11"></td>
</tr>
How do I multiply input values for hours, rate and markup and show it under total cost input using below formula. The event could be keyup.
Initially, totalcost = hours * rate
Case 1: If markup (%) > 0, for eg: 10%, then markup_cost = (hours * rate * markup) / 100
totalcost = (hours * rate) + markup_cost
Case 2: If markup (%) < 0, for eg: -10%, then markup_cost = (hours * rate * markup) / 100
totalcost = (hours * rate) - markup_cost
Try to use starts with selector like,
$(function(){
function setTotalCost(n){
var h=Number($('#hours_'+n).val()),
m=Number($('#markup_'+n).val()), // taking 0 if empty
r=Number($('#rate_'+n).val());
$('#totalcost_'+n).val(h*m*r);
}
$('[id^="rate_"]').on('keyup',function(){
var n = this.id.replace('rate_','');// get the number
setTotalCost(n);
});
$('[id^="markup_"]').on('keyup',function(){
var n = this.id.replace('markup_','');// get the number
setTotalCost(n);
});
});
$(function(){
function setTotalCost(n){
var h=Number($('#hours_'+n).val()),
m=Number($('#markup_'+n).val()), // taking 0 if empty
r=Number($('#rate_'+n).val());
$('#totalcost_'+n).val(h*m*r);
}
$('[id^="rate_"]').on('keyup',function(){
var n = this.id.replace('rate_','');// get the number
setTotalCost(n);
});
$('[id^="markup_"]').on('keyup',function(){
var n = this.id.replace('markup_','');// get the number
setTotalCost(n);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="addr1">
<td>John Doe</td>
<td>
<input type="text" readonly="" value="80" id="hours_10">
</td>
<td>
<input type="text" value="" id="rate_10">
</td>
<td>
<input type="text" value="" id="markup_10">
</td>
<td>
<input type="text" readonly="" value="" id="totalcost_10">
</td>
</tr>
<tr id="addr2">
<td>Foo User</td>
<td>
<input type="text" readonly="" value="80" id="hours_11">
</td>
<td>
<input type="text" value="" id="rate_11">
</td>
<td>
<input type="text" value="" id="markup_11">
</td>
<td>
<input type="text" readonly="" value="" id="totalcost_11">
</td>
</tr>
</table>

Update total in table row with jquery

I have a table
<table>
<tbody>
<tr>
<td><input type="text" name="quantity" /></td>
<td><input type="text" name="price" /></td>
<td><input type="text" name="total" disabled />
</tr>
<tr>
<td><input type="text" name="quantity" /></td>
<td><input type="text" name="price" /></td>
<td><input type="text" name="total" disabled />
</tr>
<tr>
<td><input type="text" name="quantity" /></td>
<td><input type="text" name="price" /></td>
<td><input type="text" name="total" disabled />
</tr>
<tr>
<td><input type="text" name="quantity" /></td>
<td><input type="text" name="price" /></td>
<td><input type="text" name="total" disabled />
</tr>
</tbody>
</table>
How can I update the total input field when a change in quantity or price happens?
I have thought of something like
$('table tbody tr td').filter(':nth-child(1), :nth-child(2)').children('input').change(function() {
$(this).parent('td').siblings('td').filter(':nth-child(3)').val(?);
});
but it seems a bit unhandy.
You can use:
$('table tbody tr td').find('input').keyup(function() {
var total=0;
total=(parseInt($(this).parent('td').siblings('td').not(':nth-child(3)').find('input').val())||0)+(parseInt($(this).val())||0);
$(this).closest('tr').find('input:last').val(total)
});
Working Demo
Much easy to read and control if you can assign some dummy class to quantity, price and total input.
Something like this:
HTML
<table>
<tbody>
<tr>
<td><input type="text" class="qty" name="quantity" /></td>
<td><input type="text" class="prc" name="price" /></td>
<td><input type="text" class="total" name="total" disabled />
</tr>
<tr>
<td><input type="text" class="qty" name="quantity" /></td>
<td><input type="text" class="prc" name="price" /></td>
<td><input type="text" class="total" name="total" disabled />
</tr>
<tr>
<td><input type="text" class="qty" name="quantity" /></td>
<td><input type="text" class="prc" name="price" /></td>
<td><input type="text" class="total" name="total" disabled />
</tr>
<tr>
<td><input type="text" class="qty" name="quantity" /></td>
<td><input type="text" class="prc" name="price" /></td>
<td><input type="text" class="total" name="total" disabled />
</tr>
</tbody>
</table>
Script
$('table tbody tr').find('.qty, .prc').on('keyup',function() {
var parent = $(this).parents('tr');
var quantity = parseInt(parent.find('.qty').val())||0;
var price = parseInt(parent.find('.prc').val())||0;
parent.find('.total').val(quantity*price);
});
Check working example here
Personally, i prefer not to select elements by their position. If you wind up changing them later, or adding another your code is broken.
I would do something like:
$(this).closest('tr').find('input[name=total]').val(?);

Is it posible to get all the values of the text boxes with the same name?

I have a doubt in javascript. Is it posible to get the values of text boxes with the same name ?
for example
<INPUT TYPE="text" NAME="inputbox" VALUE="">
<INPUT TYPE="text" NAME="inputbox" VALUE="">
these text boxes have same name, how can i get its values by name ?
OK, lemme come to the real problem i got, hope am explaining correctly.
I have a series of text boxes which i gotta validate now. Its not a big deal to validate textboxe normally.
But this is an array of text boxes where the id of the text boxes will be available only when the fields are added dynamically by clicking on the + button. when the press button is clicked the whole set of text boxes will appear. as many times its clicked, it will get added.
So its imposible to get the values to validate with the ID, so i tried by name.
JAVASCRIPT FUNCTION
function insComep()
{
// $("#doctorPri").validationEngine("updatePromptsPosition")
// jQuery("#doctorPri").validationEngine('attach', {promptPosition : "topRight"});
rl=document.getElementById("compeTable").rows.length;
var a=document.getElementById("compeTable").insertRow(rl);
var g=a.insertCell(0);
var f=a.insertCell(1);
var m=a.insertCell(2);
var n=a.insertCell(3);
var o=a.insertCell(4);
var p=a.insertCell(5);
var q=a.insertCell(6);
var r=a.insertCell(7);
var s=a.insertCell(8);
var t=a.insertCell(9);
//var v=a.insertCel1l(11);
//var u=a.insertCell(12);
g.innerHTML='<select name="competproduct[]" style="width:86px" id="competproduct'+rl+'" class="validate[required]" ><option value="">--Select--</option><?echo $product_str;?></select>';
f.innerHTML='<input type="text" name="competcompany[]" id="competcompany'+rl+'" size="10" class="validate[required]" >';
m.innerHTML='<input type="text" name="competbrand[]" id="competbrand'+rl+'" size="10" class="validate[required]" >';
n.innerHTML='<input type="text" name="competdrug[]" id="competdrug'+rl+'" size="10" class="validate[required]" >';
o.innerHTML='<input type="text" name="competquty[]" id="competquty'+rl+'" size="2" class="validate[required,custom[integer]] text-input" >';
p.innerHTML='<input type="text" name="competprice_frm[]" id="competprice_frm'+rl+'" size="2" class="validate[required,custom[number],funcCall[getPriceFromE]] text-input" />';
q.innerHTML='<input type="text" name="competprice_to[]" id="competprice_to'+rl+'" size="2" class="validate[required,custom[number],funcCall[getPriceTo]] text-input" />';
r.innerHTML='<input type="text" name="competmrp[]" id="competmrp'+rl+'" size="2" class="validate[required,custom[number],funcCall[getMrp]] text-input"/>';
s.innerHTML='<select name="ChemistParma[]" style="width:86px" id="ChemistParma'+rl+'" style="width:86px" ><option value="">--Select--</option><?echo $chemist_str;?></select>';
t.innerHTML='<img src="media/images/details_close.png" onClick="delCompe('+rl+'); "/>';
// jQuery("#doctorPri").validationEngine('attach', {promptPosition : "topRight"});
$("#doctorPri").validationEngine('hideAll');
}
HTML
<table width="100%" id='compeTable' border='0' style='margin-left:auto;margin-right:auto;margin-top:40px;' >
<tr style="border-bottom:1px solid #999999;"><td colspan='4'>
<div style="background:;padding:3px;text-align:left; ">
<font color='black'><strong >Competitor Detail(s):</strong></font><font color="red">*</font>
</div>
</td></tr>
<tr>
<td>Product Name:<font color="red">*</font></td>
<td>Company Name:<font color="red">*</font></td>
<td>Brand Name:<font color="red">*</font></td>
<td>Drug Name:<font color="red">*</font></td>
<td> Quantity:<font color="red">*</font></td>
<td>Pricefrom Dist:<font color="red">*</font></td>
<td >Price to Dist:<font color="red">*</font></td>
<td> MRP:<font color="red">*</font></td>
<td>Chemist<font color="red">*</font><input type='button'value='+' style='width:1px' style='width:1px' onclick='frame5()'/>
</td>
<td></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>
<select name='competproduct[]' id='competproduct' style="width:86px" class="validate[required]" >
<option value=''>-select Product-</option>
<? echo $product_str;?>
</select>
</td>
<td>
<input type="text" name="competcompany[]" id="competcompany" size="10" class="validate[required]" >
</td>
<td ><input type="text" name="competbrand[]" id="competbrand" size="10" class="validate[required]" >
</td>
<td><input type="text" name="competdrug[]" id="competdrug" size="10" class="validate[required]" >
</td>
<td><input type="text" name="competquty[]" id="competquty" size="2" class="validate[required,custom[integer]] text-input" >
</td>
<td>
<input type="text" name="competprice_frm[]" id="competprice_frm" size="2" class="validate[required,custom[number],funcCall[getPriceFromE]] text-input" />
</td>
<td>
<input type="text" name="competprice_to[]" id="competprice_to" size="2" class="validate[required,custom[number],funcCall[getPriceTo]] text-input" />
</td>
<td><input type="text" name="competmrp[]" id="competmrp" size="2" class="validate[required,custom[number],funcCall[getMrp]] text-input" onBlur=''/>
</td>
<td>
<select name='ChemistParma[]' id='ChemistParma' style="width:86px">
<option value=''>-select chemict-</option>
<?echo $chemist_str?>
</select></td>
<td>
<img src="media/images/details_open.png" onClick="insComep()"/>
</td>
</tr>
</table>
It's quite simple,
document.getElementsByName("inputBox");
You can use a multitude of different methods.
1) Manual traversal of childNodes etc, and checking for nodeName. This is pretty involved and requires a lot of boring code, so I won't write an example of that here.
2) document.getElementsByTagName. This can also be used on DOM nodes, so you can do something like document.getElementById("my_form").getElementsByTagName("input"), depending on how the rest of the DOM looks of course.
3) document.querySelectorAll("input"). The string argument is a full CSS selector. Some older browsers doesn't support this though.
Here is example for you with your code:
<div id="inputs">
<INPUT TYPE="text" NAME="inputbox" VALUE="asd">
<INPUT TYPE="text" NAME="inputbox" VALUE="efs">
</div>
<script>
$(document).ready(function () {
var howmany = $('#inputs').children("input").length;
alert(howmany);
for( i=0; i<= howmany-1; i++ ) {
var input = $("#inputs").children("input").eq(i).attr('VALUE');
alert(input);
}
});
</script>

Categories

Resources