This question already has answers here:
JavaScript and getElementById for multiple elements with the same ID
(13 answers)
Closed 1 year ago.
I have a JavaScript function, that uses the id on
3 textboxes to get their numerical values, add all of them together and give me the result on the last textbox. I am also getting a list of people on my DB and I am using Foreach row to get all names and then create the 4 textboxes that the user can input the values and get the result. The problem is that I can only get the first row to show the result, the rest doesn't show.
<tbody>
<?php
if ($accao_formandos->num_rows()>0){
foreach ($accao_formandos->result() as $row){
?>
<tr>
<td>
<input type="text" class="form-control" name="formandos" id="formandos" onkeyup="sum();" data-fieldgroup="fg-formandos" data-error-msg="" value="<?php echo $row->nome; ?>" readonly>
</td>
<td>
<input type="text" class="form-control" name="n_faltas" id="n_faltas" onkeyup="sum();" data-fieldgroup="fg-n_faltas" data-error-msg="" value="<?php //echo $n_faltas; ?>">
</td>
<td>
<input type="text" class="form-control" name="assiduidade" id="assiduidade" onkeyup="sum();" data-fieldgroup="fg-assiduidade" data-error-msg="" value="<?php //echo $pauta_assiduidade; ?>">
</td>
<td>
<input type="text" class="form-control" name="participacao_tarefas" id="participacao_tarefas" onkeyup="sum();" data-fieldgroup="fg-participacao_tarefas" data-error-msg="" value="<?php //echo $pauta_participacao_tarefas; ?>">
</td>
<td>
<input type="text" class="form-control" name="elaboracao_trabalho" id="elaboracao_trabalho" onkeyup="sum();" data-fieldgroup="fg-elaboracao_trabalho" data-error-msg="" value="<?php //echo $pauta_elaboracao_trabalho; ?>">
</td>
<td>
<input type="text" class="form-control" name="classificacao_quant" id="classificacao_quant" data-fieldgroup="fg-classificacao_quant" data-error-msg="" value="" readonly>
</td>
</tr>
<?php
}
}
?>
</tbody>
function sum(result) {
var assiduidade = document.getElementById('assiduidade').value;
var participacao_tarefas = document.getElementById('participacao_tarefas').value;
var elaboracao_trabalho = document.getElementById('elaboracao_trabalho').value;
var result = (parseInt(assiduidade)*10 + parseInt(participacao_tarefas)*30 + parseInt(elaboracao_trabalho)*60) / 100;
if (!isNaN(result)) {
document.getElementById('classificacao_quant').value = result;
}
}
JavaScript function is getting called at the end of body maybe that helps.
I read here on another post, that document.querySelector doesn't work because it gets the first element, but I am using getElementByid but its probably that. If someone can help out, I would appreciate it
Thanks for all the help in advance.
You can almost always dispense with ID attributes, especially when you involve loops and generating content. querySelector and querySelectorAll when used in conjunction with other selector functions (parentNode,nextSibling etc) allow for easy identification of elements so you can also dispense with the old fashioned inline event handlers and assign an external event listener to all elements as per the below code snippet.
The snippet uses dummy data for the name and various fields believed to be numeric in nature
document.querySelectorAll('tr input:not([data-result])').forEach(input => {
input.addEventListener('keyup', function(e) {
let tr = this.parentNode.parentNode;
let ass = tr.querySelector('input[name="assiduidade"]');
let par = tr.querySelector('input[name="participacao_tarefas"]');
let ela = tr.querySelector('input[name="elaboracao_trabalho"]');
let res = tr.querySelector('input[data-result]');
let result = ( (Number(ass.value) * 10) + (Number(par.value) * 30) + (ela.value * 60) ) / 100;
if (!isNaN(result) ) res.value = result;
})
})
[type='text']{width:80px;}
<table>
<tr>
<td>
<input type="text" class="form-control" name="formandos" data-fieldgroup="fg-formandos" data-error-msg="" value="Fred" readonly />
</td>
<td>
<input type="text" class="form-control" name="n_faltas" data-fieldgroup="fg-n_faltas" data-error-msg="" value="" />
</td>
<td>
<input type="text" class="form-control" name="assiduidade" data-fieldgroup="fg-assiduidade" data-error-msg="" value="23" />
</td>
<td>
<input type="text" class="form-control" name="participacao_tarefas" data-fieldgroup="fg-participacao_tarefas" data-error-msg="" value="64" />
</td>
<td>
<input type="text" class="form-control" name="elaboracao_trabalho" data-fieldgroup="fg-elaboracao_trabalho" data-error-msg="" value="41" />
</td>
<td>
<input type="text" class="form-control" name="classificacao_quant" data-result=true data-fieldgroup="fg-classificacao_quant" data-error-msg="" value="" readonly />
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" name="formandos" data-fieldgroup="fg-formandos" data-error-msg="" value="Barny" readonly />
</td>
<td>
<input type="text" class="form-control" name="n_faltas" data-fieldgroup="fg-n_faltas" data-error-msg="" value="" />
</td>
<td>
<input type="text" class="form-control" name="assiduidade" data-fieldgroup="fg-assiduidade" data-error-msg="" value="68" />
</td>
<td>
<input type="text" class="form-control" name="participacao_tarefas" data-fieldgroup="fg-participacao_tarefas" data-error-msg="" value="21" />
</td>
<td>
<input type="text" class="form-control" name="elaboracao_trabalho" data-fieldgroup="fg-elaboracao_trabalho" data-error-msg="" value="88" />
</td>
<td>
<input type="text" class="form-control" name="classificacao_quant" data-result=true data-fieldgroup="fg-classificacao_quant" data-error-msg="" value="" readonly />
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" name="formandos" data-fieldgroup="fg-formandos" data-error-msg="" value="Betty" readonly />
</td>
<td>
<input type="text" class="form-control" name="n_faltas" data-fieldgroup="fg-n_faltas" data-error-msg="" value="" />
</td>
<td>
<input type="text" class="form-control" name="assiduidade" data-fieldgroup="fg-assiduidade" data-error-msg="" value="88" />
</td>
<td>
<input type="text" class="form-control" name="participacao_tarefas" data-fieldgroup="fg-participacao_tarefas" data-error-msg="" value="14" />
</td>
<td>
<input type="text" class="form-control" name="elaboracao_trabalho" data-fieldgroup="fg-elaboracao_trabalho" data-error-msg="" value="57" />
</td>
<td>
<input type="text" class="form-control" name="classificacao_quant" data-result=true data-fieldgroup="fg-classificacao_quant" data-error-msg="" value="" readonly />
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" name="formandos" data-fieldgroup="fg-formandos" data-error-msg="" value="Wilma" readonly />
</td>
<td>
<input type="text" class="form-control" name="n_faltas" data-fieldgroup="fg-n_faltas" data-error-msg="" value="" />
</td>
<td>
<input type="text" class="form-control" name="assiduidade" data-fieldgroup="fg-assiduidade" data-error-msg="" value="8" />
</td>
<td>
<input type="text" class="form-control" name="participacao_tarefas" data-fieldgroup="fg-participacao_tarefas" data-error-msg="" value="12" />
</td>
<td>
<input type="text" class="form-control" name="elaboracao_trabalho" data-fieldgroup="fg-elaboracao_trabalho" data-error-msg="" value="88" />
</td>
<td>
<input type="text" class="form-control" name="classificacao_quant" data-result=true data-fieldgroup="fg-classificacao_quant" data-error-msg="" value="" readonly />
</td>
</tr>
</table>
Your HTML is technically invalid. An ID is only allowed to be used once. Try something like this:
Change your loop to foreach ($accao_formandos->result() as $key => $row) to get a unique key for each row.
Change your inputs to look like id="assiduidade<?= $key ?>" onkeyup="sum(<?= $key ?>);" so that they all have a unique ID, and pass the key to your function.
Prototype for your function should become function sum(key) (you never previously passed in a parameter to it, so the "result" in there isn't doing anything).
And finally change every element reference to include the key, like getElementById('assiduidade' + key).
Related
The problem I'm facing is related with Invoicing system. There is one row exists by default but if there are more than one products then user can Add New Item which adds the new row with jQuery append function.
Invoicing system has few Inputs one of them is Item Name which autocomplete by Typehead JS.
Code of Predefined Row
<tbody id="TableBody">
<tr>
<td style="width: 220px">
<input type="text" class="form-control Item" name="Item" id="Item" placeholder="Nombre del producto" required autocomplete="off">
</td>
<td>
<input type="number" name="QTV" min="1" name="QTV" id="QTV" class="form-control text-right" placeholder="00" required>
</td>
<td>
<input step="2" type="number" class="form-control text-right" min="1" id="Rate" placeholder="0.00" readonly>
</td>
<td>
<input step="any" id="Disc" name="Disc" type="number" min="0" name="" class="form-control text-right" placeholder="00">
</td>
<td>
<input type="text" name="SubTotal" class="form-control text-right" id="Total" placeholder="Total" readonly>
</td>
<td>
<button type="button" class="btn btn-danger DelRow">Delete</button>
</td>
</tr>
</tbody>
Code to Add new Row
$('#AddNewItem').click(function() { $('#TableBody').append(`
<tr>
<td style='width: 220px'>
<input type='text' class='form-control Item' name='Item' id='Item' placeholder='Nombre del producto' required autocomplete='off'>
</td>
<td>
<input type='number' name='QTV' min='1' name='QTV' id='QTV' class='form-control text-right' placeholder='00' required>
</td>
<td>
<input step='2' type='number' class='form-control text-right' min='1' id='Rate' placeholder='0.00' readonly>
</td>
<td>
<input step='any' id='Disc' name='Disc' type='number' min='0' name='' class='form-control text-right' placeholder='00'>
</td>
<td>
<input type='text' name='SubTotal' class='form-control text-right' id='Total' placeholder='Total' readonly>
</td>
<td>
<button type="button" class="btn btn-danger DelRow">Delete</button>
</td>
</tr>
`); });
Code to show Auto suggestions
$(document).ready(function() {
$('.Item').typeahead({
source: function (query, process) {
return $.get('FetchItem.php?Item', { query: query }, function (data) {
data = $.parseJSON(data);
return process(data);
});
},
});
});
I just wanted to show suggestions on all the additional appended fields.
Any help would be much appreciated, Thank you
Screenshot
Afterall, I got the solution to my answer.
I was using jQuery document load function which was not working on the appended rows.
So instead of $(document).ready(function() { I just used $('.TableBody').on("click", ".Item", function() { and it worked.
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>
Hi I am using codeigniter framework. I am having a javascript to to create a table row dynamically when I click a button.
I need to have a dropdown inside a table cell that is added dynamically. Here is the code I tried so far.
function displayResult() {
<?php
$attributes = array('class' => 'form-horizontal', 'id' => '');
$options_employee = array('' => "Select");
foreach ($employee as $row)
{
$options_employee[$row['first_name']] = $row['first_name'];
}
?>
var something='<?php echo form_dropdown('employee', $options_employee, set_value('employee[]'), 'class="span2"');?>';
alert(something);
var row = document.getElementById("test").insertRow(-1);
row.innerHTML = '<td><div>'+something+'</div></td><td><input type="text" name="start_time[]" value="" style="width:35px;"/></td><td><input type="text" name="pid[]" style="width:35px;"/></td><td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td><td><input type="text" class="type" value="" style="width:45px;"/></td><td><input type="text" class="qty_prch" value="" style="width:45px;"/></td><td><input type="text" class="qty_used" value="" style="width:45px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td>';
}
When button is clicked I call this displayResult(). I am getting 2 errors in my console.
1.Uncaught SyntaxError: Unexpected token ILLEGAL
2.Uncaught ReferenceError: displayResult is not defined
Can someone help me? Please help me fix this code.
function displayResult() { <? php
$attributes = array('class' => 'form-horizontal', 'id' => '');
$options_employee = array('' => "Select");
foreach($employee as $row) {
$options_employee[$row['first_name']] = $row['first_name'];
}
?>
var something = '<?php echo form_dropdown('
employee ', $options_employee, set_value('
employee[]
'), '
class = "span2"
');?>';
alert(something);
var row = document.getElementById("test").insertRow(-1);
row.innerHTML = '<td><div>' + something + '</div></td><td><input type="text" name="start_time[]" value="" style="width:35px;"/></td><td><input type="text" name="pid[]" style="width:35px;"/></td><td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td><td><input type="text" class="type" value="" style="width:45px;"/></td><td><input type="text" class="qty_prch" value="" style="width:45px;"/></td><td><input type="text" class="qty_used" value="" style="width:45px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td>';
}
<div id="form">
<!-- div form starts here.its for add table -->
<table id="test">
<thead>
<tr>
<td style="width:80px;">
employee
</td>
<td style="width:35px;">
start time
</td>
<td style="width:35px;">
id
</td>
<td style="width:145px;">
Description
</td>
<td style="width:45px;">
Type
</td>
<td style="width:45px;">
qty prch
</td>
<td style="width:45px;">
qty used
</td>
<td style="width:70px;">
Price
</td>
<td style="width:70px;">
discount
<td style="width:70px;">
Tax
</td>
<td style="width:70px;">
Total
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<?php echo form_dropdown( 'employee', $options_employee, set_value( 'employee[]'), 'class="span2"');?>
</td>
<td>
<input type="text" name="start_time[]" value="" style="width:35px;" />
</td>
<td>
<input type="text" name="pid[]" value="" style="width:35px;" />
</td>
<td>
<input type="text" name="description[]" class="description" value="" style="width:145px;" />
</td>
<td>
<input type="text" name="type[]" class="type" style="width:45px;" />
</td>
<td>
<input type="text" name="qty_prch[]" class="qty_prch" style="width:45px;" />
</td>
<td>
<input type="text" name="qty_used[]" class="qty_used" style="width:45px;" />
</td>
<td>
<input type="text" name="price[]" class="price" style="width:70px;" />
</td>
<td>
<input type="text" name="discount[]" class="discount" style="width:70px;" />
</td>
<td>
<input type="text" name="tax[]" class="tax" style="width:70px;" />
</td>
<td>
<input type="text" name="total[]" class="total" style="width:70px;" />
</td>
</tr>
</tbody>
</table>
<div id="add_row">
<button onClick="displayResult()" class="add_r"></button>
</div>
This works fine for me. Thank you all for your support !!
function displayResult() {
<?php
$attributes = array('class' => 'form-horizontal', 'id' => '');
$options_employee = array('' => "Select");
foreach ($employee as $row)
{
$options_employee[$row['first_name']] = $row['first_name'];
}
$dropdown = form_dropdown('employee', $options_employee, set_value('employee[]'), 'class="span2"');
?>
var complex = <?php echo json_encode($dropdown); ?>;
var row = document.getElementById("test").insertRow(-1);
row.innerHTML =
'<td><div>'+complex+'</div></td>'+
'<td><input type="text" name="start_time[]" value="" style="width:35px;"/></td>'+
'<td><input type="text" name="pid[]" style="width:35px;"/></td>'+
'<td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td>'+
'<td><input type="text" class="type" value="" style="width:45px;"/></td>'+
'<td><input type="text" class="qty_prch" value="" style="width:45px;"/></td>'+
'<td><input type="text" class="qty_used" value="" style="width:45px;"/></td>'+
'<td><input type="text" value="" style="width:70px;"/></td>'+
'<td><input type="text" value="" style="width:70px;"/></td>'+
'<td><input type="text" value="" style="width:70px;"/></td>'+
'<td><input type="text" value="" style="width:70px;"/></td>';
}
Change your single ' to double "
your code is var something='<?php echo form_dropdown('employee', $options_employee, set_value('employee[]'), 'class="span2"');?>';
because when javascript start reading this line
var something='<?php echo form_dropdown('employee' it seems statement end here ('e near ' after dropdown('
you should use something like that
var something='<?php echo form_dropdown("employee", $options_employee, set_value("employee[]"), \'class="span2"\');?>';
sorry for my bad english
In your code Snippet on the first line :
function displayResult() { <? php
there is a space between <? and php
Remove that and retry.
I have the following html page and need to Sum three Rows of HTML Textbox Values Using JQuery / JavaScript.
- I need totals for each row as well as a grand total of all rows.
Here is what the form looks like:
Here is my HTML with three rows of textboxes:
<table data-role="table" data-theme="c" id="bookList" class="table-stroke table-stripe">
<thead>
<tr>
<th>Type</th>
<th>Mon<br>
<input disabled id="monDate" size="5" data-mini="true"></th>
<th>Tue<br>
<input disabled id="tueDate" size="5" data-mini="true"></th>
<th>Wed<br>
<input disabled id="wedDate" size="5" data-mini="true"></th>
<th>Thu<br>
<input disabled id="thuDate" size="5" data-mini="true"></th>
<th>Fri<br>
<input disabled id="friDate" size="5" data-mini="true"></th>
<th>Sat<br>
<input disabled id="satDate" size="5" data-mini="true"></th>
<th>Sun<br>
<input disabled id="sunDate" size="5" data-mini="true"></th>
<th>Totals</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<th><select name="select-choice-1" id="select-choice-1" data-native-menu="false" data-theme="c" data-mini="true">
<option value="Regular Hourly Rate" selected>Regular Hourly Rate</option>
<option value="Paid Leave Time">Paid Leave Time</option>
<option value="Bereavement">Bereavement</option>
<option value="Holiday Pay">Holiday Pay</option>
</select></th>
<td><input type="number" pattern="[0-9]*" name="mon1" id="mon1" value="8" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="tue1" id="tue1" value="8" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="wed1" id="wed1" value="8" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="thu1" id="thu1" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="fri1" id="fri1" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="sat1" id="sat1" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="sun1" id="sun1" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input name="total1" type="text" disabled id="total1" value="" size="10" maxlength="5" pattern="[0-9]*" data-mini="true"></td>
<td><label>
<input name="desc1" type="text" id="desc1" size="15" maxlength="50" data-mini="true">
</label></td>
</tr>
<tr>
<th><select name="select-choice-2" id="select-choice-2" data-native-menu="false" data-theme="c" data-mini="true">
<option value="Regular Hourly Rate">Regular Hourly Rate</option>
<option value="Paid Leave Time" selected>Paid Leave Time</option>
<option value="Bereavement">Bereavement</option>
<option value="Holiday Pay">Holiday Pay</option>
</select></th>
<td><input type="number" pattern="[0-9]*" name="mon2" id="mon2" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="tue2" id="tue2" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="wed2" id="wed2" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="thu2" id="thu2" value="8" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="fri2" id="fri2" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="sat2" id="sat2" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="sun2" id="sun2" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input name="total2" type="text" disabled id="total2" value="" size="10" maxlength="5" pattern="[0-9]*" data-mini="true"></td>
<td><label>
<input name="desc2" type="text" id="desc2" size="15" maxlength="50" data-mini="true">
</label></td>
</tr>
<tr>
<th><select name="select-choice-3" id="select-choice-3" data-native-menu="false" data-theme="c" data-mini="true">
<option value="Regular Hourly Rate">Regular Hourly Rate</option>
<option value="Paid Leave Time">Paid Leave Time</option>
<option value="Bereavement">Bereavement</option>
<option value="Holiday Pay" selected>Holiday Pay</option>
</select></th>
<td><input type="number" pattern="[0-9]*" name="mon3" id="mon3" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="tue3" id="tue3" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="wed3" id="wed3" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="thu3" id="thu3" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="fri3" id="fri3" value="8" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="sat3" id="sat3" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input type="number" pattern="[0-9]*" name="sun3" id="sun3" value="" size="10" maxlength="5" data- mini="true"></td>
<td><input name="total3" type="text" disabled id="total3" value="" size="10" maxlength="5" pattern="[0-9]*" data-mini="true"></td>
<td><label>
<input name="desc3" type="text" id="desc3" size="15" maxlength="50" data-mini="true">
</label></td>
</tr>
<tr>
<th> </th>
<td colspan="7"><div align="right">Totals</div></td>
<td><input name="total4" type="text" disabled id="total4" value="" size="10" maxlength="5" pattern="[0-9]*" data-mini="true"></td>
<td> </td>
</tr>
</tbody>
</table>
Assuming you have the following html
<table>
<tr id="hourly">
<td>
<input value="1" />
<input value="2" />
<input id="total_hour" />
</td>
</tr>
</table>
<button id="calc">Submit</button>
The following JS should work for your needs.
//-- Create an empty array to hold items
var items = [];
//-- set hourly total = 0
var htotal = 0;
//-- When submit is clicked process hourly time, this should be repeated for each row
$("#calc").click(function () {
//-- use the each function to loop through every input field on the hourly row
$("#hourly input").each(function () {
//-- only the final total has an id and we don't want that included in our total
if(!$(this).attr("id"))
{
//-- convert each value to a number and push to items array
items.push(parseFloat($(this).val()));
}
});
//-- loop through each item in the items array
$.each(items, function() {
//-- add the items together as the htotal variable
htotal += this;
});
//-- set the total_hour value to htotal
$("#total_hour").val(htotal);
});
Working Plunk here http://plnkr.co/edit/KbUgI9Orov5dao4fftET?p=preview
I'm working on a project that is based on an Excel spreadsheet, where I need to calculate budgets, etc. There are various categories in my table, and I need to calculate the subtotal of each category. Here's a screenshot to make it more clear:
http://i.imgur.com/loyLbW7.png
My problem is, I'm not sure how to calculate the subtoal for each category. Right now, I have $('.subcat100 .budget').each(function(). The class "subcat100" is attached to the tr and changes for each category section (subcat100, subcat200, subcat300, etc.). The numerical value is based off the sub category number stored in database. How would I pull all of these classes and iterate through them?
jQuery:
$(document).ready(function() {
$('input[name="txtQuantity[]"],input[name="txtUnitCost[]"]').change(function(e) {
var budget = 0;
var $row = $(this).parent().parent();
var quanity = $row.find('input[name="txtQuantity[]"]').val();
var unitcost = $row.find('input[name="txtUnitCost[]"]').val();
budget = parseFloat(quanity * unitcost);
var decimal = budget.toFixed(2);
$row.find('.budget').val(decimal);
var sum = 0;
$('.subcat100 .budget').each(function() {
var budgets = $(this).val();
console.log(budgets);
if (IsNumeric(budgets)) {
sum += parseFloat(budgets, 10);
}
});
$('.subcat100 .budgetsubtotal').val(sum);
});
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
});
HTML:
<table>
<tbody>
<tr class="subcat100">
<td>
<span name="txtItemCode[]"><strong>100</strong></span>
</td>
<td colspan="7">
<span name="txtSubCategoryName[]" class="100"><strong>Land Purchase Costs</strong></span>
</td>
</tr>
<tr class="subcat100">
<td>
<input type="text" name="txtSubItemCode[]" size="10" readonly="readonly" value="101">
</td>
<td>
<input type="text" name="txtItem[]" size="50" readonly="readonly" value="Purchase price">
</td>
<td>
<input type="text" name="txtUnit[]" size="10" value="">
</td>
<td>
<input type="text" name="txtQuantity[]" class="integer" size="10" value="1">
</td>
<td>
<input type="text" name="txtUnitCost[]" class="monetary" size="10" value="299.99">
</td>
<td>
<input type="text" name="txtBudget[]" class="monetary budget" size="10" readonly="readonly" value="299.99">
</td>
<td>
<input type="text" name="txtActual[]" class="monetary" size="10" value="249.99">
</td>
<td>
<input type="text" name="txtDifference[]" class="monetary difference" size="10" readonly="readonly" value="50.00">
</td>
</tr>
<tr class="subcat100">
<td>
<input type="text" name="txtSubItemCode[]" size="10" readonly="readonly" value="110">
</td>
<td>
<input type="text" name="txtItem[]" size="50" readonly="readonly" value="Realtor's fees">
</td>
<td>
<input type="text" name="txtUnit[]" size="10" value="">
</td>
<td>
<input type="text" name="txtQuantity[]" class="integer" size="10" value="">
</td>
<td>
<input type="text" name="txtUnitCost[]" class="monetary" size="10" value="">
</td>
<td>
<input type="text" name="txtBudget[]" class="monetary budget" size="10" readonly="readonly" value="">
</td>
<td>
<input type="text" name="txtActual[]" class="monetary" size="10" value="">
</td>
<td>
<input type="text" name="txtDifference[]" class="monetary difference" size="10" readonly="readonly" value="">
</td>
</tr>
<tr class="subcat100">
<td>
<input type="text" name="txtSubItemCode[]" size="10" readonly="readonly" value="120">
</td>
<td>
<input type="text" name="txtItem[]" size="50" readonly="readonly" value="Due diligence">
</td>
<td>
<input type="text" name="txtUnit[]" size="10" value="">
</td>
<td>
<input type="text" name="txtQuantity[]" class="integer" size="10" value="15">
</td>
<td>
<input type="text" name="txtUnitCost[]" class="monetary" size="10" value="45.00">
</td>
<td>
<input type="text" name="txtBudget[]" class="monetary budget" size="10" readonly="readonly" value="675.00">
</td>
<td>
<input type="text" name="txtActual[]" class="monetary" size="10" value="700.00">
</td>
<td>
<input type="text" name="txtDifference[]" class="monetary difference" size="10" readonly="readonly" value="-25.00">
</td>
</tr>
<tr class="subcat100">
<td colspan="5">
<span><strong>Subtotal</strong></span>
</td>
<td>
<input type="text" name="txtSubTotalBudget[]" class="budgetsubtotal" size="10" readonly="readonly" value="">
</td>
<td>
<input type="text" name="txtSubTotalActual[]" class="actualsubtotal" size="10" readonly="readonly" value="">
</td>
<td>
<input type="text" name="txtSubTotalDifference[]" class="differencesubtotal" size="10" readonly="readonly" value="">
</td>
</tr>
</tbody>
</table>
Well, I ended up doing this:
var itemcodes = <?php echo json_encode($arrItemCodes);?>;
$('input[name="txtQuantity[]"],input[name="txtUnitCost[]"]').change(function(e) {
var budget = 0;
var $row = $(this).parent().parent();
var quanity = $row.find('input[name="txtQuantity[]"]').val();
var unitcost = $row.find('input[name="txtUnitCost[]"]').val();
budget = parseFloat(quanity * unitcost);
$row.find('.budget').val(budget.toFixed(2));
$.each(itemcodes, function(intIndex, objValue) {
var sum = 0;
$('.subcat' + objValue + ' .budget').each(function() {
var budgets = $(this).val();
console.log(budgets);
if (IsNumeric(budgets)) {
sum += parseFloat(budgets, 10);
}
});
$('.subcat' + objValue + ' .budgetsubtotal').val(sum.toFixed(2));
});
});
Open to other suggestions!