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>
Related
Now, when a start date is selected in each row and click ok, an end date will display accordingly. So each table row has to manually click a button to show the end date.
Im wondering is it possible that if i only select one start date and click ok,
not only the first row end date is shown, but also 2nd , 3rd... etc rows' start date and end date will be automatically show accordingly to the interval days
PS: Please note that the number of rows are dynamic, coming from database and the total no of row is unknown.
Any ideas will be greatly appreciated. Thank you !!
(function($, window, document, undefined){
$(".addSkip").click(function() {
// row instance to use `find()` for the other input classes
var $row = $(this).closest('tr');
var date = new Date($row.find(".start_date").val()+" 0:00:00"),
days = parseInt($row.find(".days").val(), 10);
console.log(date.getDate());
console.log(days);
if (!isNaN(date.getTime())) {
date.setDate(date.getDate() + days);
$row.find(".end_date").val(date.toInputFormat());
} else {
alert("Invalid Date");
}
});
Date.prototype.toInputFormat = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
};
})
(jQuery, this, document);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<th>
start</th>
<th>end</th>
<th>interval</th>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<input type="button" size="10" value="ok" class="addSkip"></td>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"> </td>
</tr>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<input type="button" size="10" value="ok" class="addSkip"></td>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"> </td>
</tr>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<input type="button" size="10" value="ok" class="addSkip" ></td>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><input type="text" size="3" name="skip[]" class="days" value="10">
</tr>
</table>
desired result
start end interval
13/10/17 20/10/17 7
20/10/17 23/10/17 3
23/10/17 30/10/17 7
......
etc
I've removed the "ok" button in favour of a simpler change event (both on date_start and days) and added the logic for your need! if something is not clear, don't esitate to ask clarifications ;)
(function($, window, document, undefined){
$('input.start_date, input.days').on('change',function() {
var $row = $(this).closest('tr'),
$start = $row.find('.start_date'),
$end = $row.find('.end_date'),
$other = $row.find('.otherfield'),
$interval = $row.find('.days'),
date = new Date($start.val()+" 0:00:00"),
days = parseInt($interval.val(), 10);
console.log(date.getDate());
console.log(days);
if (!isNaN(date.getTime())) {
date.setDate(date.getDate() + days);
$end.val(date.toInputFormat());
$other.val(date.toInputFormat());
$row.next('tr')
.find('.start_date').val(date.toInputFormat()).trigger('change');
} else {
console.log("Invalid Date");
}
});
Date.prototype.toInputFormat = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
};
})
(jQuery, this, document);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>start</th>
<th>end</th>
<th>other</th>
<th>interval</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><textarea class="otherfield"></textarea></td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"> </td>
</tr>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><textarea class="otherfield"></textarea></td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"> </td>
</tr>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><textarea class="otherfield"></textarea></td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"></td>
</tr>
</tbody>
</table>
In jquery, you can do something like this to find multiple element:
$row.find("*[class^=".end_date"]")
For more details, refer jquery selectors
I have this code that doesn't work to calculate quantity * price - discount = total,
the quantity values are retrieved from a database. Why isn't the calculated total being set on the appropriate total input for the row?
<?php
$con = mysqli_connect('localhost', 'root', '', 'a.karat');
if(isset($_POST['product_id']))
{
$prno=$_POST['prno'];
$i=1;
$sql = mysqli_query($con,"select * from detail_pr where prNo='$prno'");
while ($r = mysqli_fetch_array($sql)) {
echo
'<tr>
<td><input type="checkbox" name="check[]" id="check'.$i.'" value="'.$i.'"></td>
<td><label for="productCode"></label>
<input type="text" name="productCode'.$i.'" id="productCode'.$i.'" readonly value="'.$r["productCode"].'" size="12" ></td>
<td><label for="productName"></label>
<input type="text" name="productName'.$i.'" id="productName'.$i.'" readonly value="'.$r["productName"].'"size="35" ></td>
<td><label for="qty"></label>
<input type="number" onkeyup="calc(this);" name="qty'.$i.'" id="qty'.$i.'" readonly value="'.$r["qty"].'" size="8" ></td>
<td><input type="number" onkeyup="calc(this);" name="price'.$i.'" id="price'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
<td><input type="number" onkeyup="calc(this);" name="discount'.$i.'" id="discount'.$i.'" size="10" min="0" max="99" onchange="calc(this);"></td>
<td><input type="number" name="total'.$i.'" id="total'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
</tr>';
$i++;
}
}
?>
<script>
function calc(id) {
//var row=id.parentNode.parentNode;
var quant=row.cells[4].getElementsByTagName('input')[0].value;
var price=row.cells[5].getElementsByTagName('input')[0].value;
var disc=row.cells[6].getElementsByTagName('input')[0].value;
if(disc==null || disc=='') {
res=parseFloat(quant)*parseFloat(price);
} else {
var res=(parseFloat(quant)*parseFloat(price))- (parseFloat(quant)*parseFloat(price)*(parseFloat(disc)/100));
}
row.cells[7].getElementsByTagName('input')[0].value=res;
}
</script>
There are only a couple changes to be made to have the calculated total placed in the final input of the row:
remove the single-line comment operator (i.e. //) on the first line:
function calc(id) {
//var row = id.parentNode.parentNode;
^
(Maybe this was a left-over from attempts at other ways to define row).
The indexes of the cells within the row variable are off by one. This is because
JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1.
1
so for instance, to get the value for quant, update this line:
var quant = row.cells[4].getElementsByTagName('input')[0].value;
to this:
var quant = row.cells[3].getElementsByTagName('input')[0].value;
and similarly for the values for price and disc, as well as updating the total (i.e. row.cells[6].getElementsByTagName('input')[0].value = res;)
See these changes applied in the example below:
function calc(id) {
var row = id.parentNode.parentNode;
var quant = row.cells[3].getElementsByTagName('input')[0].value;
var price = row.cells[4].getElementsByTagName('input')[0].value;
var disc = row.cells[5].getElementsByTagName('input')[0].value;
if (disc == null || disc == '') {
res = parseFloat(quant) * parseFloat(price);
} else {
var res = (parseFloat(quant) * parseFloat(price)) - (parseFloat(quant) * parseFloat(price) * (parseFloat(disc) / 100));
}
row.cells[6].getElementsByTagName('input')[0].value = res;
}
<table>
<tr>
<td></td>
<!--checkbox-->
<td>Code</td>
<td>Name</td>
<td>Quantity</td>
<td>Price</td>
<td>Discount</td>
<td>Total</td>
</tr>
<tr>
<td>
<input type="checkbox" name="check[]" id="check1" value="1">
</td>
<td>
<label for="productCode"></label>
<input type="text" name="productCode1" id="productCode1" readonly value="29" size="12">
</td>
<td>
<label for="productName"></label>
<input type="text" name="productName1" id="productName1" readonly value="wheel" size="35">
</td>
<td>
<label for="qty"></label>
<input type="number" onkeyup="calc(this);" name="qty1" id="qty1" readonly value="2" size="8">
</td>
<td>
<input type="number" onkeyup="calc(this);" name="price1" id="price1" size="10" min="1" max="99" onchange="calc(this);">
</td>
<td>
<input type="number" onkeyup="calc(this);" name="discount1" id="discount1" size="10" min="0" max="99" onchange="calc(this);">
</td>
<td>
<input type="number" name="total1" id="total1" size="10" min="1" max="99" onchange="calc(this);">
</td>
</tr>
</table>
1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Accessing_array_elements
i See that you are using row parameter in your script and it's commented. just after function calc declaration .
I have here a table that automatically compute the total cost base on the
quantity you entered.
My problem is every time I try to remove the value in quantity the total cost value
from the previous quantity is still there instead of "0". I just want it to response like this :
If the quantity textbox has a value total cost will compute and
if the user remove the value in quantity the total cost will display
"0".
Any help would be much appreciated!
Thank you.
Here's what I have so far.
HTML
<table style="border:1px solid purple">
<tr>
<th style="font-size:9px;">COST</th>
<th style="font-size:9px;">QTY</th>
<th style="font-size:9px;">TOTAL</th>
</tr>
<tr id="Tr1">
<td><input class="price" type="text" name="price[]" value="100.00"></td>
<td><input class="qty" type="text" name="qty[]" ></td>
<td><input type="text" class="output" name="output[]"></td>
</tr>
<tr id="Tr2">
<td><input class="price" type="text" name="price[]" value="100.00"></td>
<td><input class="qty" type="text" name="qty[]" ></td>
<td><input type="text" class="output" name="output[]"></td>
</tr>
<tr id="Tr3">
<td><input class="price" type="text" name="price[]" value="100.00"></td>
<td><input class="qty" type="text" name="qty[]" ></td>
<td><input type="text" class="output" name="output[]"></td>
</tr>
<tr id="Tr4">
<td><input class="price" type="text" name="price[]" value="100.00"></td>
<td><input class="qty" type="text" name="qty[]" ></td>
<td><input type="text" class="output" name="output[]"></td>
</tr>
</table>
JavaScript
$(document).ready(function() {
$(this).keyup(function() {
var grandTotal = 0;
$("input[name='price[]']").each(function (index) {
var price = $("input[name='price[]']").eq(index).val();
var qty = $("input[name='qty[]']").eq(index).val();
var output = parseInt(price) * parseInt(qty);
if (!isNaN(output)) {
$("input[name='output[]']").eq(index).val(output);
}
});
});
});
Sample here : https://jsfiddle.net/bqwnw9Lk/1/
modified jsvascript is below, try this..
$(document).ready(function() {
$(this).keyup(function() {
var grandTotal = 0;
$("input[name='price[]']").each(function (index) {
var price = $("input[name='price[]']").eq(index).val();
var qty = $("input[name='qty[]']").eq(index).val();
if( qty == ""){
output = 0;
}
else{
var output = parseInt(price) * parseInt(qty);
}
if (!isNaN(output)) {
$("input[name='output[]']").eq(index).val(output);
}
});
});
});
If u want to keep the output field empty for empty quantity field then You can set
output= "" instead of output =0;
I'm very new to JavaScript and I have an assignment that I'm unable to resolve. So I have a table with five fields and I need to calculate the total for a month, then automatically generate the yearly total in a different cell. I got to make the total work for the month but I have no idea how to reflect that in the year cells. Any help will be much appreciated. Thanks a lot for your time :)
Here's my code:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function update() {
var a = +document.forms['calc'].elements['fieldOne'].value,
b = +document.forms['calc'].elements['fieldTwo'].value,
c = +document.forms['calc'].elements['fieldThree'].value,
d = +document.forms['calc'].elements['fieldFour'].value,
e = +document.forms['calc'].elements['fieldFive'].value,
fieldTotal = ((b-d)*a)*c;
document.forms['calc'].elements['fieldTotal'].value = fieldTotal;
return false;
}
function update2() {
var f = +document.forms['calc'].elements['field6'].value,
g = +document.forms['calc'].elements['field7'].value,
h = +document.forms['calc'].elements['field8'].value,
i = +document.forms['calc'].elements['fieldFour'].value,
j = +document.forms['calc'].elements['fieldFive*12'].value,
field9=fieldFour;
field10=fieldFive*12;
fieldTotal2=fieldTotal*12;
document.write('fieldTotal2');
document.write('field9');
document.write('field10');
return false;
}
</script>
</head>
<body>
<form name="calc" action="#">
<table width="600" border="1">
<tr>
<td colspan="2"> </td>
<td width="63">Month</td>
<td width="109">Year</td>
</tr>
<tr>
<td colspan="2">Field1</td>
<td><input type="text" name="fieldOne" id="fieldOne" size="15" value="5,000" /></td>
<td><input type="text" name="field6" id="field6" size="15" value="60,000"/></td>
</tr>
<tr>
<td colspan="2">Field2</td>
<td><input type="text" name="fieldTwo" id="fieldTwo" value="3.0" size="15" /></td>
<td><input type="text" name="field7" id="field7" value="3.0" size="15" /></td>
</tr>
<tr>
<td colspan="2">Field3</td>
<td><input type="text" name="fieldThree" id="fieldThree" size="15" value="$350"/></td>
<td><input type="text" name="field8" id="field8" size="15" value="$350"/></td>
</tr>
<tr>
<td colspan="2">Field4</td>
<td><input type="text" name="fieldFour" id="fieldFour" value="1.5" size="15" /></td>
<td><input type="number" name="field9" id="field9" value="1.5" size="15" /></td>
</tr>
<tr>
<td colspan="2">Filed5</td>
<td><input type="text" name="fieldFive" id="fieldFive" size="15" value="75"/></td>
<td><input type="text" name="field10" id="field10" size="15" /></td>
</tr>
<tr>
<td width="137">Total</td>
<td width="83"><input type="button" value="Calculate" onClick="update();return false;" /></td>
<td><input type="text" name="fieldTotal" id="fieldTotal" size="15" readonly /></td>
<td><input type="text" name="fieldTotal2" id="fieldTotal2" size="15" readonly /></td>
</tr>
</table>
</form>
</body>
Based on what you described I think this should work for you.
Demo
function update() {
var frmEles = document.forms.calc.elements,
a = frmEles.fieldOne.value.replace(',',''), //Remove comma
b = frmEles.fieldTwo.value,
c = frmEles.fieldThree.value.replace('$',''), //Remove Dollar sign
d = frmEles.fieldFour.value,
e = frmEles.fieldFive.value,
fieldTotal = ((b-d)*a)*c;
//Total for the month
frmEles.fieldTotal.value = formatNumber(fieldTotal);
//Calculations for the year
frmEles.field6.value = formatNumber(a * 12);
frmEles.field7.value = formatNumber(b * 12);
frmEles.field8.value = '$' + formatNumber(c * 12); //Add back dollar sign
frmEles.field9.value = formatNumber(d * 12);
frmEles.field10.value = formatNumber(e * 12);
frmEles.fieldTotal2.value = formatNumber(fieldTotal * 12);
return false;
}
//Format the numbers with commas.
function formatNumber(n){
return n.toLocaleString();
}
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);
}