how to dynamically calculate value in the text box - javascript

i have a invoice where i have to calculate some value in the textbox using jquery.
I don't know much about Jquery. Please help me to solve this problem.
In my invoice there is quantity textbox,
if users enters the quantity then dynamically it should show the
calculated price i.e (total_subPrice= unit_price * quantity) in
another textbox called "price".
And again the total sum of all the price should be visible in the button as a Total.
please check my below html code and run it in browser then you will understand my problem exactly.
<html>
<body>
<form name="invoice form" action="saveToDatabase.java">
<table border="1" height="30%" width="30%">
<tr>
<td align="center" colspan="5">Customer Invoice</td>
</tr>
<tr>
<td width="5%" bgcolor="#CCCCCC">Sn.no.</td>
<td width="25%" bgcolor="#CCCCCC">Item</td>
<td width="25%" bgcolor="#CCCCCC">Unit Price(In $)</td>
<td width="20%" bgcolor="#CCCCCC">Quantity</td>
<td width="25%" bgcolor="#CCCCCC">Line Total<br/>(Price * Qnty)</td>
</tr>
<tr>
<td width="5%">1</td>
<td width="25%">Iphone 5S</td>
<td width="25%"><input type="text" value="400" name="unitprice1" size="4" disabled></td>
<td width="20%"><input type="text" name="quantity1" value="2" size="2"/></td>
<td width="25%"><input type="text" name="price1" value="400" size="4"/></td>
</tr>
<tr>
<td width="5%">2</td>
<td width="25%">Ipad 2</td>
<td width="25%"><input type="text" value="700" name="unitprice2" size="4" disabled></td>
<td width="20%"><input type="text" name="quantity2" value="1" size="2"/></td>
<td width="25%"><input type="text" name="price2=" value="700" size="4"/></td>
</tr>
<tr>
<td width="5%">1</td>
<td width="25%">mp3</td>
<td width="25%"><input type="text" value="50" name="unitprice1" size="4" disabled></td>
<td width="20%"><input type="text" name="quantity1" value="3" size="2"/></td>
<td width="25%"><input type="text" name="price1" value="150" size="4"/></td>
</tr>
<tr>
<td align="right" colspan="5">Total<input type="text" name="subtotal" value="1250" size="12" disabled/></td>
</tr>
</table>
</form></body>
</html>

I enjoy seeing practical examples to learn stuff like jQuery myself, so I made an example for your problem so you can see how it works: http://jsfiddle.net/bozdoz/LGyeq/
Line by line:
Select all of the input tags and call a function if they are changed:
$('input').change(function(){
create a variable to store the totals, to calculate the subtotal:
var linetotals = 0;
select each element with class 'lineTotal' (which I added, so that we could select them):
$('.lineTotal').each(function(){
Get price and quantity by finding the input elements within the same tr element (eq(#) gets the first and second element respectively):
price = $(this).parents('tr').find('input').eq(0).val();
quantity = $(this).parents('tr').find('input').eq(1).val();
Set the lineTotal class element to the new total, and add the total to lineTotals variable:
$(this).val(price*quantity);
linetotals += price*quantity;
});
Set the subtotal to the value of the linetotals variable:
$('#total').val(linetotals);
});​
This is one way you can do it. It has a lot to do with preference. Hope this is a good start.
Update
Re: Askers new request for more generalized code
Use CSS Attribute selectors to select the input fields. JSFiddle is updated with the following code:
$('input').change(function(){
var linetotals = 0;
$('[name^="price"]').each(function(){
price = $(this).parents('tr').find('input').eq(0).val();
quantity = $(this).parents('tr').find('input').eq(1).val();
$(this).val(price*quantity);
linetotals += price*quantity;
});
$('[name=subtotal]').val(linetotals);
});​

Related

Monitor the changes in table using JavaScript or HTML

I want to change the total price when the count or unit price of the products are changed on the website. I know I should use the onChange function, but I have no idea about how to write the JavaScript code.
<table id="productTable" class="layui-table">
<thead>
<tr>
<th>No.</th>
<th>PART NUMBER</th>
<th>DESCRIPTION</th>
<th>QTY(PCS)</th>
<th>UNIT PRICE (USD)</th>
<th>AMOUNT(USD)</th>
<th>OPRATION</th>
</tr>
</thead>
<tbody id="columns">
<tr style="display:none">
<td>1</td>
<td><input type="hidden" name="numberList"></td>
<td><input type="hidden" name="remarkList"></td>
<td><input type="hidden" name="countList"></td>
<td><input type="hidden" name="priceList"></td>
<td><input type="hidden" name="totalPriceList"></td>
</tr>
<tr th:each="orderProduct:${orderProducts}">
<td th:text="${orderProducts.indexOf(orderProduct)+1}"></td>
<td contenteditable="true" >
<input type="text" name="numberList" class="layui-input number" th:value="${orderProduct.number}">
</td>
<td contenteditable="true" >
<input type="text" name="remarkList" class="layui-input remark" th:value="${orderProduct.remark}">
</td>
<td id="productCoun" contenteditable="true" >
<input id="productCount" type="text" name="countList" onchange="update()" class="layui-input count"
th:value="${orderProduct.count}">
</td>
<td id="normalPric" contenteditable="true" >
<input id="normalPrice" type="text" name="priceList" onchange="update()" class="layui-input price"
th:value="${orderProduct.price}">
</td>
<td id="totalPric" th:text="${orderProduct.price}*${orderProduct.count}">
<input id="total" type="text" name="totalPriceList" class="layui-input price"
th:text="${orderProduct.price}*${orderProduct.count}">
</td>
<td>
Edit
<a href="javascript:void(0)" class="delBtn redType" onclick='delColumns(this)'>Del</a>
</td>
</tr>
</tbody>
</table>
I hope that the totalPrice = count*price could refresh whenever the user changes one of those values.
You can easily monitor the pointed input fields (#productCount and #normalPrice) and change the value of #total according to it. In the code below, I use the input event and I'm not using inline event handlers, but rather the function addEventListener() (know why).
const productCountInput = document.querySelector('#productCount');
const productPriceInput = document.querySelector('#normalPrice');
const totalPriceInput = document.querySelector('#total');
function updateTotalPrice() {
totalPriceInput.value = (parseFloat(productCountInput.value) * parseFloat(productPriceInput.value)) || 0;
}
productCountInput.addEventListener('input', updateTotalPrice);
productPriceInput.addEventListener('input', updateTotalPrice);
<table id="productTable" class="layui-table">
<thead>
<tr>
<th>No.</th>
<th>PART NUMBER</th>
<th>DESCRIPTION</th>
<th>QTY(PCS)</th>
<th>UNIT PRICE (USD)</th>
<th>AMOUNT(USD)</th>
<th>OPRATION</th>
</tr>
</thead>
<tbody id="columns">
<tr style="display:none">
<td>1</td>
<td><input type="hidden" name="numberList"></td>
<td><input type="hidden" name="remarkList"></td>
<td><input type="hidden" name="countList"></td>
<td><input type="hidden" name="priceList"></td>
<td><input type="hidden" name="totalPriceList"></td>
</tr>
<tr th:each="orderProduct:${orderProducts}">
<td th:text="${orderProducts.indexOf(orderProduct)+1}"></td>
<td contenteditable="true">
<input type="text" name="numberList" class="layui-input number" th:value="${orderProduct.number}">
</td>
<td contenteditable="true">
<input type="text" name="remarkList" class="layui-input remark" th:value="${orderProduct.remark}">
</td>
<td id="productCoun" contenteditable="true">
<input id="productCount" type="text" name="countList" class="layui-input count" th:value="${orderProduct.count}">
</td>
<td id="normalPric" contenteditable="true">
<input id="normalPrice" type="text" name="priceList" class="layui-input price" th:value="${orderProduct.price}">
</td>
<td id="totalPric" th:text="${orderProduct.price}*${orderProduct.count}">
<input id="total" type="text" name="totalPriceList" class="layui-input price" th:text="${orderProduct.price}*${orderProduct.count}">
</td>
<td>
Edit
Del
</td>
</tr>
</tbody>
</table>

How to pass the selected checkbox rows to a function

I have to pass the selected rows to a function( ). From the below code, I am able to get the value of selected checkbox but could not get the entire row. Please help me on how to get the entire selected rows and pass those rows to a function.
my html code:
<div id ="div_table">
<table id="myTable">
<tr>
<th>SELECT</th>
<th>BANKID</th>
<th>EFFECTIVE SAVE DATE</th>
<th>SAVE MONTH</th>
<th>MONTH OF SUBMISSION</th>
<th>PILLAR</th>
<th>LEVER</th>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1000" id="1000"></td>
<td id="bank" >100000</td>
<td id="edate">10-02-2009</td>
<td id="month">Jan</td>
<td id="subMonth"><input type="text" id="subMonth"></td>
<td id="pillar"><input type="text" id="pillar1"></td>
<td id="lever"><input type="text" id="lever1"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1001" id="1001"></td>
<td id="bank1" >100001</td>
<td id="edate1">12-12-2010</td>
<td id="month1">Feb</td>
<td id="subMonth1"><input type="text" id="subMonth2"></td>
<td id="pillar1"><input type="text" id="pillar2"></td>
<td id="lever1"><input type="text" id="lever12"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1002" id="1002"></td>
<td id="bank2" >100002</td>
<td id="edate2">18-02-2018</td>
<td id="month2">Apr</td>
<td id="subMonth2"><input type="text" id="subMonth3"></td>
<td id="pillar2"><input type="text" id="pillar3"></td>
<td id="lever2"><input type="text" id="lever13"></td>
</tr>
</table>
</div>
My jQuery Code:
$('#div_table').click(function() {
var result = []
$('input:checkbox:checked', tableControl).each(function() {
result.push($(this).parent().next().text());
});
alert(result);
});
The selected rows should be passed to the below function:I have to use these rows one by one and store.
function invokeAllEligibleSaves(result){
alert(result)
}
It will be very much useful for me If i get a working code. Thanks in advance.
One way to achieve that is like this:
First : get a reference to the input element that triggered the function. From this element, you can reach the .closest() parent that has the tag <tr>.
Second: This can then be queried for all of its <td> .children() and each child will either have .text() or .html() to report back. I think in your case, you are interested in the text part.
Third: You will need to push all .text() values in a separate array, that will be your row. Then push that row into another array result. So your result will be an array of arrays.
$('#div_table').click(function() {
var result = [] // create an empty array for all rows
$('input:checkbox:checked').each(function() {
var row = []; // create an empty array for the current row
//loop through all <td> elements in that row
$(this).closest('tr').children('td').each(function(){
// add .text() or .html() if you like
row.push($(this).text());
});
// now push that row to the result array
result.push(row);
});
alert(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="div_table">
<table id="myTable">
<tr>
<th>SELECT</th>
<th>BANKID</th>
<th>EFFECTIVE SAVE DATE</th>
<th>SAVE MONTH</th>
<th>MONTH OF SUBMISSION</th>
<th>PILLAR</th>
<th>LEVER</th>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1000" id="1000"></td>
<td id="bank">100000</td>
<td id="edate">10-02-2009</td>
<td id="month">Jan</td>
<td id="subMonth"><input type="text" id="subMonth"></td>
<td id="pillar"><input type="text" id="pillar1"></td>
<td id="lever"><input type="text" id="lever1"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1001" id="1001"></td>
<td id="bank1">100001</td>
<td id="edate1">12-12-2010</td>
<td id="month1">Feb</td>
<td id="subMonth1"><input type="text" id="subMonth2"></td>
<td id="pillar1"><input type="text" id="pillar2"></td>
<td id="lever1"><input type="text" id="lever12"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1002" id="1002"></td>
<td id="bank2">100002</td>
<td id="edate2">18-02-2018</td>
<td id="month2">Apr</td>
<td id="subMonth2"><input type="text" id="subMonth3"></td>
<td id="pillar2"><input type="text" id="pillar3"></td>
<td id="lever2"><input type="text" id="lever13"></td>
</tr>
</table>
</div>
You just need an additional .parent() in your result.push statement to get the whole row, because you're only getting the cell so far:
result.push($(this).parent().parent().next().text());
This would be a more effective solution for your problem. The drawback with the accepted answer is, it will get triggered whenever & wherever you click inside the table (even when you click on a text).
Here it gets updated only when a checkbox is selected.
$(document).ready(function() {
$('input:checkbox').on('change', function() {
var result = [];
$('input:checkbox:checked').each(function() {
var rowText = '';
$(this).parent().siblings().each(function() {
rowText += $(this).text() + ' ';
});
result.push(rowText.trim());
});
alert(JSON.stringify(result));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id ="div_table">
<table id="myTable">
<tr>
<th>SELECT</th>
<th>BANKID</th>
<th>EFFECTIVE SAVE DATE</th>
<th>SAVE MONTH</th>
<th>MONTH OF SUBMISSION</th>
<th>PILLAR</th>
<th>LEVER</th>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1000" id="1000"></td>
<td id="bank" >100000</td>
<td id="edate">10-02-2009</td>
<td id="month">Jan</td>
<td id="subMonth"><input type="text" id="subMonth"></td>
<td id="pillar"><input type="text" id="pillar1"></td>
<td id="lever"><input type="text" id="lever1"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1001" id="1001"></td>
<td id="bank1" >100001</td>
<td id="edate1">12-12-2010</td>
<td id="month1">Feb</td>
<td id="subMonth1"><input type="text" id="subMonth2"></td>
<td id="pillar1"><input type="text" id="pillar2"></td>
<td id="lever1"><input type="text" id="lever12"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1002" id="1002"></td>
<td id="bank2" >100002</td>
<td id="edate2">18-02-2018</td>
<td id="month2">Apr</td>
<td id="subMonth2"><input type="text" id="subMonth3"></td>
<td id="pillar2"><input type="text" id="pillar3"></td>
<td id="lever2"><input type="text" id="lever13"></td>
</tr>
</table>
</div>

append parent names and ids of textboxes to newly generated ones

I'm able to generate more textboxes for user to input variables on click of a link. what i've noticed is when the new row of textboxes are generated, it generates with name text and id as id. But i want it to have the same names of the original or parent textboxes.
<table width="80%" border="0" align="center" cellpadding="5" cellspacing="5">
<tr>
<td bgcolor="#CCCCFF"><strong>4. VECHICLE INFORMATION</strong></td>
<td bgcolor="#CCCCFF"> </td>
<td bgcolor="#CCCCFF"> </td>
<td bgcolor="#CCCCFF"><div align="right"><a class="add_more" href="#">Add More Vechicles</a></div></td>
</tr>
<tr id="more_vechicle">
<td bgcolor="#FFFFFF"><input type="text" name="vechicle_name[]" id="vechicle_name" class="register-input" placeholder="Name of Vechicle" /></td>
<td bgcolor="#FFFFFF"><input type="text" name="vechicle_type[]" id="vechicle_type" class="register-input" placeholder="Type of Vechicle" /></td>
<td bgcolor="#FFFFFF"><input type="text" name="vechicle_registration[]" id="vechicle_registration" class="register-input" placeholder="Registration No." /></td>
<td bgcolor="#FFFFFF"><input type="text" name="vechicle_color[]" id="vechicle_color" class="register-input" placeholder="Color of Vechicle" /></td>
</tr>
<tr>
<td colspan="4" bgcolor="#FFFFFF"><div align="center">
<input type="submit" name="button" id="button" value="Save & Continue" />
</div></td>
</tr>
</table>
JS
$(document).ready(function()
{
$('.add_more').click(function(){
var id=$(':text').length;
$('#more_vechicle td').append('<input class="register-input" type="text" id='+id+' name="text'+id+'">');
});
});
Use a .each() loop to loop over the TDs. Then you can get the first input that's in each TD, clone it, and give it a new ID.
$('.add_more').click(function() {
$('#more_vechicle td').each(function() {
var these_inputs = $(this).find(".register-input");
var id = these_inputs.length;
var new_input = these_inputs.first().clone(true).val('');
new_input.attr('id', function(i, old_id) {
return old_id + id;
});
$(this).append(new_input);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="80%" border="0" align="center" cellpadding="5" cellspacing="5">
<tr>
<td bgcolor="#CCCCFF"><strong>4. VECHICLE INFORMATION</strong></td>
<td bgcolor="#CCCCFF"> </td>
<td bgcolor="#CCCCFF"> </td>
<td bgcolor="#CCCCFF"><div align="right"><a class="add_more" href="#">Add More Vechicles</a></div></td>
</tr>
<tr id="more_vechicle">
<td bgcolor="#FFFFFF"><input type="text" name="vechicle_name[]" id="vechicle_name" class="register-input" placeholder="Name of Vechicle" /></td>
<td bgcolor="#FFFFFF"><input type="text" name="vechicle_type[]" id="vechicle_type" class="register-input" placeholder="Type of Vechicle" /></td>
<td bgcolor="#FFFFFF"><input type="text" name="vechicle_registration[]" id="vechicle_registration" class="register-input" placeholder="Registration No." /></td>
<td bgcolor="#FFFFFF"><input type="text" name="vechicle_color[]" id="vechicle_color" class="register-input" placeholder="Color of Vechicle" /></td>
</tr>
<tr>
<td colspan="4" bgcolor="#FFFFFF"><div align="center">
<input type="submit" name="button" id="button" value="Save & Continue" />
</div></td>
</tr>
</table>
The solution you're looking for is jquery's clone() function (http://api.jquery.com/clone/). Just clone #more_vehicle and insert it before the continue button.
$('.add_more').click(function() {
$('#more_vechicle').clone()
.attr('id', null) /* removing id attribute for the cloned
* tr so there is only one elemnt with that id
*/
.insertBefore('#append_anchor');
Be aware that the default behavior of clone() is to not copy event handler from the parent element.
I'd also suggest to make sure every car gets it's own tr. See the following fiddle:
https://jsfiddle.net/jcvnos9w/

javascript calculator with click to calculate

I have a working calculator on my website that is used for business expense savings estimation. currently the calculator auto-calculates in real time as the user inputs numbers. i would like the user to have to click a calculate button in order to see any results. could someone please help as i am having a hard time adjusting the code myself. here is the current code:
function calc() {
var cost = document.getElementById('phone').value * (.30) +
document.getElementById('energy').value * (.05) +
document.getElementById('cell').value * (.30) + document.getElementById('office').value * (.15) + document.getElementById('card').value *
(.35) + document.getElementById('waste').value * (.5) +
document.getElementById('payroll').value * (.5);
document.getElementById('cost').value = (cost * 12).toFixed(2);
}
<form name="form1" method="post" action="">
<table width="33%" align="center">
<tr>
<td valign="top" style="text-align: center"><strong>
Category</strong>
</td>
<td style="text-align: center"><strong>Monthly Expenses</strong>
</td>
</tr>
<tr>
<td valign="top"> </td>
<td> </td>
</tr>
<tr>
<td width="47%" valign="top">Telephone & Internet</td>
<td width="53%">
<input name="phone" id="phone" type="text" onchange="calc
()" />
</td>
</tr>
<tr>
<td valign="top">Energy</td>
<td>
<input name="energy" id="energy" type="text" onchange="calc()" />
</td>
</tr>
<tr>
<td valign="top">Cell Phone</td>
<td>
<input name="cell" id="cell" type="text" onchange="calc()" />
</td>
</tr>
<tr>
<td valign="top">Office Supplies</td>
<td>
<input name="office" id="office" type="text" onchange="calc()" />
</td>
</tr>
<tr>
<td valign="top">Merchant Card Fees</td>
<td>
<input name="card" id="card" type="text" onchange="calc()" />
</td>
</tr>
<tr>
<td valign="top">Waste Removal</td>
<td>
<input name="waste" id="waste" type="text" onchange="calc()" />
</td>
</tr>
<tr>
<td height="31" valign="top">3rd Party Payroll Fees</td>
<td>
<input name="payroll" id="payroll" type="text" onchange="calc
()" />
</td>
</tr>
<tr>
</tr>
</table>
<p> </p>
<div align="center">
<table width="33%" border="0">
<tr>
<td width="54%" height="31" valign="top"><strong>Estimated Annual
Savings:</strong>
</td>
<td width="46%">
<textarea name="cost" rows="1" id="cost" readonly style="overflow:hidden" input type="number"></textarea>
</td>
</tr>
Currently, your inputs are set up to call calc() whenever their onchange event is fired. This happens whenever the value is changed and the input is blurred (no longer in focus).
Remove the onchange="calc()" attribute on all your inputs, and add a button whever it makes sense to on your page with onclick="calc()":
<button onclick="calc()">Calculate</button>
Place button with Javascript event outside form
<button onclick="calc();">Calculate</button>
Delete all onchange="calc()" and add this html code to your page, that's it.
<button onclick="calc()">Calculate Expenses</button>
Remove the call to onchange="calc()" from all.
Put <div align="center">
<table width="33%" border="0">
<tr>
<td align="Center">
<input type="button" value="Click To Calculate" onclick="calc()" />
</td>
</tr>
</div>

Perform Dynamic Table Calculations in HTML - jQuery?

I have an HTML table which allows the user to enter some values, either directly or from a select menu.
<form action="" method="">
<table id="scores" width="358" border="1">
<tr>
<th colspan="5">Activities</th>
</tr>
<tr class="header">
<td width="104">Activity</td>
<td width="163">Rating</td>
<td width="69">Hours Per Week</td>
<td width="163">Weeks Per Year</td>
<td width="163">Average Hours Per Week</td>
</tr>
<tr>
<td class="title"><input type="text" value=""/></td>
<td><select name="rating">
<option value=""></option>
<option value="High">High</option>
<option value="Moderate">Moderate</option>
</select></td>
<td class="title"><input type="text" value=""/></td>
<td class="title"><input type="text" value=""/></td>
<td> </td>
</tr>
<tr>
<td class="title"><input type="text" value=""/></td>
<td><select name="rating">
<option value=""></option>
<option value="High">High</option>
<option value="Moderate">Moderate</option>
</select></td>
<td class="title"><input type="text" value=""/></td>
<td class="title"><input type="text" value=""/></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td class="title">Total High</td>
<td class="title" id="totalHigh"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td class="title">Total Moderate</td>
<td class="title" id="totalModerate"></td>
</tr>
<tr>
<td colspan="5"><button class="copy" value="Set Value">Submit</button></td>
</tr>
</table>
I need to perform a couple of calculations as follows:
for each row I need to calculate the "Average Hours Per Week" which is simply the (Hours Per Week * Weeks Per Year)/52
for each row the user can select either "High" or "Moderate" for the Rating. I need to then calculate the total of the "Average Hours Per Week" for all rows where Rating = "High" and all rows where Rating = "Moderate".
I've spent the better part of today pulling out my last remaining hairs trying to get something working using jQuery which I'm a newbie with. I've setup a jsfiddle at:
http://jsfiddle.net/tZPDr/
which has a simplified version of the table. Would greatly appreciate any help about how to go about performing these 2 calculations dynamically as the user types.
Many thanks,
Steve
Did a few tweaks, check out this fiddle. Rest you should be able to figure it out. :)
If you want to do this as user types, you need to bind onto keypress or keydown.
Example:
$('td.hours input').on('keypress', function() {
//get the values and calculate
});
Then choose you fields and perform the calculations. You can get the values like this
Example:
var hrs = $('td.hours input').val();

Categories

Resources