jquery multiply and divide at the same time - javascript

Here are my text fields
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="form_textfield" class="price" autocomplete="off" /></td>
</tr>
<tr>
<td>Liters:</td>
<td><input type="text" name="liters" id="form_textfield" class="liters" autocomplete="off" /></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" name="jqueryamount" id="form_textfield" class="jqueryamount" autocomplete="off" /></td>
</tr>
Currently when you input price and liters, it multiplies them and outputs the answer to jqueryamount textfield it works well. What i want to do is when i type in the amount and the price it will divide the jqueryamount field with the price field and output it to liters field.
UPDATE FIXED
// JavaScript Document
$(document).ready(function(){
$('.price').keyup(calculate);
$('.liters').keyup(calculate);
});
function calculate(e)
{
$('.jqueryamount').val($('.price').val() * $('.liters').val());
}
// JavaScript Document
$(document).ready(function(){
$('.jqueryamount').keyup(calculate1);
$('.price').keyup(calculate1);
});
function calculate1(e)
{
$('.liters').val($('.jqueryamount').val() / $('.price').val());
}
JUST ADDED A NEW NAME FOR THE DIVIDE FUNCTION... silly me thanks for the help guys
Here are my javascript
// JavaScript Document
$(document).ready(function(){
$('.price').keyup(calculate);
$('.liters').keyup(calculate);
});
function calculate(e)
{
$('.jqueryamount').val($('.price').val() * $('.liters').val());
}
// JavaScript Document
$(document).ready(function(){
$('.jqueryamount').keyup(calculate);
$('.price').keyup(calculate);
});
function calculate(e)
{
$('.liters').val($('.jqueryamount').val() / $('.price').val());
}
My problem is when adding the divide function the multiplication part will no longer work, i can no longer type inside the liters textfield it gives me NaN error.

Use parseFloat() function after the get the value from input, which converts string to number.
When you put the value price and amount the liters would show like this.
$('.price').keyup(calculateLiters, calculateAmount);
$('.jqueryamount').keyup(calculateLiters);
$('.liters').keyup(calculateAmount);
function calculateLiters(e) {
price = parseFloat($('.price').val());
amount = parseFloat($('.jqueryamount').val());
if(!isNaN(price) && !isNaN(amount)){
$('.liters').val(amount / price);
}
}
function calculateAmount(e) {
price = parseFloat($('.price').val());
liters = parseFloat($('.liters').val());
if(!isNaN(price) && !isNaN(liters)){
$('.jqueryamount').val(price * liters);
}
}
Demo

I swapped some class names and id's to make code more efficient.
HTML
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="price" class="form_textfield" autocomplete="off" /></td>
</tr>
<tr>
<td>Liters:</td>
<td><input type="text" name="liters" id="liters" class="form_textfield" autocomplete="off" /></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" name="jqueryamount" id="jqueryamount" class="form_textfield" autocomplete="off" /></td>
</tr>
Javascript
// JavaScript Document
$(document).ready(function(){
$('.form_textfield').keyup(calculate);
});
function calculate()
{
$('#jqueryamount').val($('#price').val() * $('#liters').val());
$('#liters').val($('#jqueryamount').val() / $('#price').val());
}
Here is a working demo. http://jsfiddle.net/vnaDK/

Related

enter key to follow the tabindex (in scenario where enter key is changed to behave as tab)

I have a 3x3 table within a form. By default tab key moves the cursor in horizontal directions on these input fields. When a tabindex is given ( Like in the example below) the tab key moves cursor columns wise instead of row wise, as I needed.
With various sources from SO answers, I came up with the Jquery to use enter key as tab. But, could not figure out how to follow the tabindex as achieved above , i.e by pressing enter key instead of cursor moving row-wise, i want it to move in column wise. Below is what I have so far, any help is appreciated.
Demo of how it currently works. http://jsfiddle.net/unCu5/125/
Source of below code: jquery how to catch enter key and change event to tab
<table>
<tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr>
</table>
$('input').live("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
})
#Dekel solution work for the html scenario he displayed, but I have a different type of HTML on view source. How do I fix this
Instead of just focus the next input element, you can find the next element (based on the tabindex) and focus on him:
$('input[tabindex^="2"]');
Check this example:
$(document).ready(function () { // Will only run once the page Document Object Model (DOM) is ready for JavaScript code
// Create a jQuery object containing the html element 'input'
// Create a .not() method to exclude buttons for keypress event
$(":input:not(:disabled)").not($(":button")).keypress(function(evt) {
// If the keypress event code is 13 (Enter)
if (evt.keyCode == 13) {
// get the attribute type and if the type is not submit
itype = $(this).prop('type');
if (itype !== 'submit') {
currentTabindex = $(this).attr('tabindex');
if (currentTabindex) {
nextInput = $('input[tabindex^="'+ (parseInt(currentTabindex)+1) +'"]');
if (nextInput.length) {
nextInput.focus();
return false;
}
}
}
}
});
});
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<table>
<tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="4" placeholder="4" /></td>
<td><input tabindex="7" placeholder="7" /></td>
</tr><tr>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="5" placeholder="5" /></td>
<td><input tabindex="8" placeholder="8" /></td>
</tr><tr>
<td><input tabindex="3" placeholder="3" /></td>
<td><input tabindex="6" placeholder="6" /></td>
<td><input tabindex="9" placeholder="9" /></td>
</tr>
</table>
The code doesn't support go back from the last input to the first. You will need to write it explicitly.
Updated version - fix wrong tabindex values
The original question didn't mention that tabindex could repeat or don't have sequential values.
This code will "fix" the values of tabindex based on the order in the code AND the values of the tabindex. It will support both repeated tabindex values and non sequential values (1, 2, 3, 6, 7):
function fixTabIndex() {
// Find all inputs. Their order will be the same order they appear inside your html.
inputs = $('input');
// Save the original HTML order of the inputs (we need this to compare their order in the HTML in case or equal two tabindex
inputs_original = $('input');
// Sort the inputs by their tabindex values and their position in the DOM
// More info on Array.prototype.sort: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
inputs.sort(function(a, b) {
if ($(a).attr('tabindex') == $(b).attr('tabindex')) {
// If tabindex is equal - sort by the position in the DOM
if (inputs_original.index(a) < inputs_original.index(b)) {
return -1;
} else {
return 1;
}
} else if ($(a).attr('tabindex') < $(b).attr('tabindex')) {
return -1;
} else {
return 1;
}
});
// Set the new value of the tabindex based on the position in the sorted array
inputs.each(function(i, el) {
$(el).attr('tabindex', i+1);
});
}
$(document).ready(function () {
// First we need to fix the tabindex values:
fixTabIndex();
$("input").keypress(function(evt) {
// If the keypress event code is 13 (Enter)
if (evt.keyCode == 13) {
// Make sure this is not a submit input
if ($(this).prop('type') !== 'submit') {
currentTabindex = $(this).attr('tabindex');
if (currentTabindex) {
nextInput = $('input[tabindex^="'+ (parseInt(currentTabindex)+1) +'"]');
if (nextInput.length) {
nextInput.focus();
return false;
}
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr>
</table>

JavaScript multiple auto count for cashier apps?

I have a page like this:
[http://jsfiddle.net/ph75fggo/]
[http://jsfiddle.net/ph75fggo/5/]//more reliable sample
And I tried to make a simple cashier apps, with help of JavaScript make an auto count on both rows and columns.
This is the result I want to get:
http://jsfiddle.net/wrz8bc10/
My Final Trying: jsfiddle.net
Your Question is not drawing the clear picture of your requirement. As far as I understand, you need to have a gross amount after deducting the discount for each row and the total discounted and net amounts at the end.
First thing that you should do is to assign a common class to each of the child of every tr. It makes your JS code a lot simpler. Otherwise you need write some extra LOC to select specific element.
<tr>
<td><input type='text' class="amount" id='harga2' value='250000' /></td>
<td><input type='text' class="discount" id='diskon2' value='' /></td>
<td><input type='text' class="grossAmount" id='total2' value='' /></td>
</tr>
<tr>
<td><input type='text' class="amount" id='harga2' value='250000' /></td>
<td><input type='text' class="discount" id='diskon2' value='' /></td>
<td><input type='text' class="grossAmount" id='total2' value='' /></td>
</tr>
<tr>
<td><input type='text' class="amount" id='harga2' value='250000' /></td>
<td><input type='text' class="discount" id='diskon2' value='' /></td>
<td><input type='text' class="grossAmount" id='total2' value='' /></td>
</tr>
After that you can use the following function:
function myFunction(){
var amounts = document.getElementsByClassName("amount");
var discounts = document.getElementsByClassName("discount");
var gAmounts = document.getElementsByClassName("grossAmount");
var lv,rowSum,totDis=0,totAmount=0;
for(lv=0;lv>gAmounts.length;lv++){
rowSum += (parseInt(amounts[lv].value)-parseInt(discounts[lv].value));
totAmount += rowSum;
totDis += parseInt(discounts[lv].value);
gAmounts[lv].value = totAmount;
}
}
But if you don't want change your HTML, Then you can use the following code:
function myFunc(){
var lv,rowSum,totDis=0,totAmount=0;
var TRs = document.getElementsByTagName("table")[0].childNodes; //assuming that the table is the first one on your page.
var lv;
for(lv=1;lv<tab.length;lv++){ // starting the counter with 1 as the first child of the table contains headings
rowSum += (parseInt(TRs[lv][0].value)-parseInt(TRs[lv][1].value));
totAmount += rowSum;
totDis += parseInt(TRs[lv][1].value);
TRs[lv].value = rowSum;
}
}
You were getting the elements with ids 'id1' and 'id2' whereas there are no such elements present in your html with those ids, they should be 'harga1' and 'diskon1'. Also, when you write your JS in a function, make sure to call it at the end, but you don't need to write it in a function in this specific case, so here is your solution:
var rows = document.getElementById("myTable").getElementsByTagName("tr").length;
for(var i=1; i<rows; i++){
var harga = parseInt(document.getElementById('harga'+i).value);
var diskon = parseInt(document.getElementById('diskon'+i).value);
var total = harga - diskon;
document.getElementById('total'+i).value = total;
}
Get the number of rows, then keep getting the harga and diskon values one by one.. harga1, harga2, harga3.. ('harga'+i) subtract their values and put them in total1, total2 and total 3.. this will work if you add more rows as well..
See the DEMO here
I have updated the JSFiddle here:
[http://jsfiddle.net/ph75fggo/4/]
This is just one approach at what you are trying to do, where I changed your code as little as possible, and still uses hard coded variable names (instead of the above answer that automatically iterates over all rows). You can use my answer to help simply extend your cashier application.
do you mean like this link?
you can change use the parameters if you want
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td>Total Harga</td>
<td>Total Diskon</td>
<td>Total Bayar</td>
</tr>
<tr>
<td><input type='text' id='harga1' onchange="dynamic()" value='250000' /></td>
<td><input type='text' id='diskon1' value='50' /></td>
<td><input type='text' id='total1' value='' /></td>
</tr>
<tr>
<td><input type='text' id='harga2' value='250000' /></td>
<td><input type='text' id='diskon2' value='0' /></td>
<td><input type='text' id='total2' value='0' /></td>
</tr>
<tr>
<td><input type='text' id='harga3' value='250000' /></td>
<td><input type='text' id='diskon3' value='0' /></td>
<td><input type='text' id='total3' value='0' /></td>
</tr>
</table>
</body>
<script>
function dynamic(){
var harga1 = document.getElementById('harga1').value;
var diskon1 = document.getElementById('diskon1').value/100;
var totalharga = harga1 - (harga1 * diskon1);
document.getElementById("total1").value = totalharga;
}
</script>
</html>

Multiple onchange and addition

I'm working on creating a page in which someone could calculate their Net Worth by entering various values. The input text will show a .00 afterwards if no decimal point is added in. I'm having troubles in getting a sum of all of the values.
Java:
<script type="text/javascript"><!--
function updatesum() {
document.form.TotalAssets.value = (document.form.CashOnHand.value -0) + (document.form.CashInChecking.value -0);
}
//-->
</script>
HTML:
<input type="text" onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'" onchange="format(this); updatesum()" onkeyup="format(this)" maxlength="11" value="0" name="CashOnHand" /></td>
</tr>
<tr>
<td><strong>Cash in Checking</strong></td>
<td>$
<input type="text"
onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'" onchange="format(this); updatesum()" onkeyup="format(this)" maxlength="11" value="0" name="CashInChecking" /></td>
</tr>
<tr>
<td align="right"><strong>Total Assets</strong></td>
<td>$<input name="TotalAssets" readonly ></td>
</tr>
It's not giving me a sum of the the values that I'm adding.
I think this is because document.form is undefined, but this one works:
function updatesum() {
var hand = parseFloat(document.forms[0].CashOnHand.value);
var checking = parseFloat(document.forms[0].CashInChecking.value);
document.forms[0].TotalAssets.value = hand - checking;
}

Jquery: sum input text fields

I have a table including input text fields with the basic structure below. I am having trouble building a function to iterate all rows in the table and sum all the values of input fields beginning with BFObel where the value of the field beginning with BFOkto are the same. So for the basic example below the sum for value 1111 would be 2000 and the sum for value 1112 would be 3000. Each sum would then be written to an inputfield with the id field1111, field1112 etc...
<table>
<tr id="BFOrow1">
<td><input type="text" id="BFOtxt1" value="text"/></td>
<td><input type="text" id="BFOkto1" value="1111" /></td>
<td><input type="text" id="BFObel1" value="1000" /></td>
</tr>
<tr id="BFOrow2">
<td><input type="text" id="BFOtxt2" value="text"/></td>
<td><input type="text" id="BFOkto2" value="1111" /></td>
<td><input type="text" id="BFObel2" value="1000" /></td>
</tr>
<tr id="BFOrow3">
<td><input type="text" id="BFOtxt3" value="text"/></td>
<td><input type="text" id="BFOkto3" value="1112" /></td>
<td><input type="text" id="BFObel3" value="1000" /></td>
</tr>
<tr id="BFOrow4">
<td><input type="text" id="BFOtxt4" value="text"/></td>
<td><input type="text" id="BFOkto4" value="1112" /></td>
<td><input type="text" id="BFObel4" value="1000" /></td>
</tr>
<tr id="BFOrow5">
<td><input type="text" id="BFOtxt5" value="text"/></td>
<td><input type="text" id="BFOkto5" value="1112" /></td>
<td><input type="text" id="BFObel5" value="1000" /></td>
</tr>
</table>
You'll want to use an object literal to track your results and an "attribute starts with" selector to find the text inputs:
var accumulator = { };
$('table input[id^=BFOkto]').each(function() {
var sum_id = this.id.replace(/^BFOkto/, 'BFObel');
if(!accumulator[this.value])
accumulator[this.value] = 0;
accumulator[this.value] += parseInt($('#' + sum_id).val(), 10);
});
// accumulator now has your results.
Don't forget the second argument to parseInt() so that you don't get tripped up by values with leading zeros (which look like octal without a specified radix).
For example: http://jsfiddle.net/ambiguous/QAqsQ/ (you'll need to run this in a browser with an open JavaScript console to see the resulting accumulator).
var sum1111 = 0;
$('input[value="1111"]').each(function() {
var ordinal = $(this).attr('id').replace('BFOkto', '');
sum1111 += parseInt($('#BFObel' + ordinal).val());
});
At the end, sum1111 should equal 2000.
For reuse, wrap the logic in a function:
function getSum(BFOkto) {
var sum = 0;
var ordinal = null;
$('input[value="' + BFOkto + '"]').each(function() {
ordinal = $(this).attr('id').replace('BFOkto', '');
sum += parseInt($('#BFObel' + ordinal).val());
});
return sum;
}
And then call:
getSum('1111');
getSum('1112');
A different approach: find all input fields with prefix BFOkto, for each, find the input with prefix BFObel sharing same parent and accumulate its value
ref = $("table td input[id^=BFOkto]");
var sums = new Object();
ref.each(function(){
val = parseInt($(this).closest('tr').find("td input[id^=BFObel]").val(), 10);
property = 'i'+ this.value;
sums[property] = (sums[property] || 0 ) + val;
});
alert(sums['i1111']);
alert(sums['i1112']);
sums will be an object with properties
i1111 = 2000
i1112 = 3000
Despite javascript allows it, it is better not to use pure numeric properties for objects (associative arrays), hence the i prefix
The running example is here:
http://jsfiddle.net/TbSau/1/

Calculate summation from data in input fields by using javascript

I'm starting at learning javascript and I have a problem
here is my html code:
<tr>
<td>
Qty1 : <input class="txt" type="number" id="qty1"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id1"></td>
</tr>
<tr>
<td>
Qty2 : <input class="txt" type="number" id="qty2"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id2"></td>
</tr>
<tr>
<td>
Qty3 : <input class="txt" type="number" name="qty" id="qty3"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id3"></td>
</tr>
<br><br>
<tr>
<td>Summation of value : </td>
<td><span id="sums">0</span></td>
</tr>
and here is my js code
/* get data */
qty1.oninput = function() {
var inputF1 = document.getElementById("id1");
inputF1.value = qty1.value*2;
};
qty2.oninput = function() {
var inputF2 = document.getElementById("id2");
inputF2.value = qty2.value*3;
};
qty3.oninput = function() {
var inputF3 = document.getElementById("id3");
inputF3.value = qty3.value;
};
/* calculate sumation */
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".getPrice").each(function() {
$(this).on('input',function(){
calculateSum();
});
});
calculateSum();
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".getPrice").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sums").html(sum.toFixed(2));
}
My problem is that when I click on the Qty input fields then the summation should be calculated. However, I have to enter values for the value input fields for my calculate function works.
How I can fix it? My expected result is that when I input the qyt input field it must calculate the summation and return the result.
For example, when I entered 1 in Qty1 field the summation should be 2 then I entered 3 in Qty2 the summation should return 11 and so on.
Thank you for your help!
my demo code: https://jsfiddle.net/1c0r6uhd/
You will have to call calculateSum after each value field is updated. Currently, you call it on the input event, which is fired before the actual value has been updated. Here is an example:
$('#qty1').on('input', function() {
$('#id1').val(this.value * 2).change();
})
$('#qty2').on('input', function() {
$('#id2').val(this.value * 3).change();
});
$('#qty3').on('input', function() {
$('#id3').val(this.value).change();
});
$('.getPrice').change(function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".getPrice").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sums").html(sum.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>
Qty1 : <input class="txt" type="number" id="qty1"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id1"></td>
</tr>
<tr>
<td>
Qty2 : <input class="txt" type="number" id="qty2"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id2"></td>
</tr>
<tr>
<td>
Qty3 : <input class="txt" type="number" name="qty" id="qty3"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id3"></td>
</tr>
<br><br>
<tr>
<td>Summation of value : </td>
<td><span id="sums">0</span></td>
</tr>
</tbody>
</table>

Categories