Javascript onChange sum input after percentage - javascript

<form name="cost">
<table border="1">
<tr>
<td>Cost</td>
<td><input type="text" name="cost" /></td>
</tr>
<tr>
<td>Discount</td>
<td><input type="text" name="discount" /> (<span id="discount2"></span>)%</td>
</tr>
<tr>
<td>Net Cost</td>
<td><input type="text" name="net" /></td>
</tr>
</table>
</form>
Hello guys,
I really need a help of javascript programming. The process of the form are:
Put a number of in Cost
Then put a number of discount (auto calculates span#discount2=cost*discount/100)
Net cost auto update = Cost-Discount
I tried many times but have no luck plus lack of javascript knowledge. Please help.

First, create a function to do that
function calculateDiscount()
{
var cost = document.getElementById('cost').value;
var discount = document.getElementById('discount').value;
//do the math
var net = cost-discount;
//update
document.getElementById('discount2').innerHTML = cost*(discount/100);
document.getElementById('net').value = net;
}
You'll also need to update your html, to add ID's to all elements and also call the function
<form name="cost">
<table border="1">
<tr><td>Cost</td><td><input type="text" id="cost" name="cost" onChange="calculateDiscount(); return false;" /></td></tr>
<tr><td>Discount</td><td><input onChange="calculateDiscount(); return false;" type="text" id="discount" name="discount" /> (<span id="discount2"></span>)%</td></tr>
<tr><td>Net Cost</td><td><input type="text" name="net" id="net" /></td></tr>
</table>
</form>

Related

I need to add together multiple inputs, which are read only totals of 2 other inputs

I am needing help in basically adding together the sum total inputs, to make them add together to create a final amount.
As you can see in the image above, there can be multiple inputs, and the person can add more with the click of the button, the code works so the quantity and the unit price add together, however I am after the subtotals adding together automatically to keep updating the gbp total.
<table>
<tr>
<td>
<input type="number" oninput="calculate(this)" id="qid1" data-quantity name="qamount" min="0" data-validation="number" class="qinput txt" value="{{Quantity}}" />
</td>
<td>
<input type="text" data-validation="length" data-validation-length="max100" class="dinput" value="{{Details}}" />
</td>
<td>
<input type="number" oninput="calculate(this)" id="uid1" data-unitprice name="uamount" min="0" data-validation="number" data-validation-allowing="float" class="uinput txt" value="{{UnitPrice}}" />
</td>
<td>
<input readonly id="subsubtotal" name="totalamount" class="sinput txt" value="{{Subtotal}}" />
</td>
</tr>
</table>
<div class="additembtton">
<button id="bttonitem">Add Invoice Item</button>
<input id="bttonitem1" type="submit" value="Save" />
<span class="gbptotal">GBP Total</span>
<span id="totalplus" class="totalsub">£0.00</span>
</div>
JS
//code that multiplies the quantity and unit price input boxes
function calculate(obj) {
var tr = obj.parentNode.parentNode;
var myBox1 = tr.cells[0].children[0].value;
var myBox2 = tr.cells[2].children[0].value;
var result = tr.cells[3].children[0];
var myResult = parseFloat(myBox1) * parseFloat(myBox2);
result.value = myResult.toFixed(2);
}
The javascript above is what works already, this multiplies both the quantity and unit price together, I am struggling with how I would do the same with the sub total, to add all the sub totals together (however many there may be), and display the final total in where the £0.00 is.
<input id="bttonitem1" type="submit" value="Save" onclick="gbpTotal()">
function gbpTotal(){
var total = 0;
var inputs = document.querySelectorAll('.sinput');
inputs.forEach(function(e){
total += parseFloat(e.value);
});
document.querySelector('#totalplus').textContent = total;
};
You might want to trigger the function anytime they click out of an input instead of on the save
You'll need to query for all the inputs that are from the same column when it's time to total them up. This is best achieved by ensuring that the inputs in each column belong to the same CSS class. This way, it doesn't matter how many rows you wind up with and you won't have to worry about rows or cells, just inputs that belong to the same class.
So, here's an example that shows how to get the total of the total column, but the same approach would be used for any other columns.
var totals = document.querySelectorAll(".total");
var output = document.getElementById("total");
var btn = document.querySelector("button");
btn.addEventListener("click", function(){
var tot = null;
// Convert the node list of inputs that hold totals into an array and loop through that array
Array.prototype.slice.call(totals).forEach(function(element){
// Get the sum of the values
tot += parseFloat(element.value);
});
// Display the output
output.textContent = tot;
});
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="name"></td>
<td><input type="text" class="price"></td>
<td><input type="text" class="qty"></td>
<td><input type="text" class="total"></td>
</tr>
<tr>
<td><input type="text" class="name"></td>
<td><input type="text" class="price"></td>
<td><input type="text" class="qty"></td>
<td><input type="text" class="total"></td>
</tr>
<tr>
<td><input type="text" class="name"></td>
<td><input type="text" class="price"></td>
<td><input type="text" class="qty"></td>
<td><input type="text" class="total"></td>
</tr>
</tbody>
</table>
<div id="total"></div>
<button>Get Totals</button>

Calculation between controls array using jquery

I am creating 2 dynamic controls array.
<input type=text name=quantity[]>
<input type=text name=price[]>
I want to multiply these two inputs and show the result accordingly. I want to do it on frontend using javascript or jQuery.
What will be the best possible way of doing it?
EDIT
#Zeus
As I mentioned in the question it is an array of controls so the code will go like this
<input type="text" name="quantity[]"> <input type="text" name="price[]">
<input type="text" name="quantity[]"> <input type="text" name="price[]">
<input type="text" name="quantity[]"> <input type="text" name="price[]">
Now I will enter quantity in first textfield and price in the second one. For each row I need to multiply these fields and show the result next to them.
Hope it explains the question more.
You can do it like this :
$("button").click(function() {
$("#calc tr").each(function(i) {
var result = $(this).find("input[name*='quantity[]']").val() * $(this).find("input[name*='price[]']").val();
$(this).children("td:nth-child(3)").html(result);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<table id="calc">
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Result</th>
</tr>
<tr>
<td>
<input type="text" name="quantity[]">
</td>
<td>
<input type="text" name="price[]">
</td>
<td></td>
</tr>
<tr>
<td>
<input type="text" name="quantity[]">
</td>
<td>
<input type="text" name="price[]">
</td>
<td></td>
</tr>
<tr>
<td>
<input type="text" name="quantity[]">
</td>
<td>
<input type="text" name="price[]">
</td>
<td></td>
</tr>
</table>
<button>Click me after entering values</button>
Run the code to test it.
This is just an example you will be needing to edit the code to make it work for you.

Re-Using JavaScript Function

Creating a cake ordering form, and the # of cakes available can vary from month to month. I am attempting to tweak a JS function created from #Anderson Contreira but in my fiddle it does not work. Here is what I have thus far - Why does nothing change when I enter a quantity?
https://jsfiddle.net/2uack1w6/
Syntax
JS
function calculate(el){
var quantity = el.val();
var id = el.attr("id").replace("item_","").replace("_qty","");
var data = {quantity: quantity,id:id};
var targetTax = $("#item_"+id+"_tax");
var targetTotalPrice = $("#item_"+id+"_totalprice");
$.post($.post(window.alert("It's been one or two or three entered");
});
}
var qty = $("#item_1_qty");
var qty1 = $("#item_2_qty");
var qty2 = $("#item_3_qty");
qty.on("keyup",function(){
window.alert("It's been one or two or three entered");
});
HTML/PHP
<body>
<form id="Form1" runat="server">
<div id="Form1" runat="server">
<table id="table1" border="1">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Tax</th>
<th>Total</th>
</tr>
<tr>
<td><label for="lblChoccake">Choc Cake</label></td>
<td><label for="lblitem1price">$25.00</label></td>
<td><input type="text" id="item_1_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_1_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_1_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
<tr>
<td><label for="lblLemonFudgecake">Lemon Fudge Cake</label></td>
<td><label for="lblitem2price">$15.00</label></td>
<td><input type="text" id="item_2_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_2_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_2_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
<tr>
<td><label for="lblCoconut">Coconut Cake</label></td>
<td><label for="lblitem3price">$35.00</label></td>
<td><input type="text" id="item_3_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_3_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_3_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
</table>
</div>
</form>
</body>
jQuery(function($) {
var qty = $("#item_1_qty");
var qty1 = $("#item_2_qty");
var qty2 = $("#item_3_qty");
qty.on("keyup",function(){
alert("It's been one or two or three entered");
});
});
Try this, you are assigning variables before the document has actually loaded.
Take a look here: https://jsfiddle.net/andersoncontreira/mtu6syby/1/
You can make some changes and will work well:
Add a class in each input of item_?_qty e.g.: <input type="text" id="item_1_qty" class="item_qty" />
In your javascript, you can leave the call generic:
jQuery(document).ready(function(){
//you can use a class for help you
$(".item_qty").on("keyup",function(){
//window.alert("It's been one or two or three entered");
calculate($(this));
});
});

issues in html when calling 2 javascript functions at a time

I have an HTML file related to a javascript file.
In this javascript file, I have 3 functions which 2 of them will be called onload of the body.
These 2 functions are meant to type a string, each of them in a different textarea.
But, when Testing this, the two strings that are typed by these js functions, are unreadable
To clarify my issue: the string must be like this:
verification step 3 of 4 passed…
enter serial number
when I call the 2 functions onload of the body, it gives me this:
vrfcto f4pse..
ne eilnme..
I can't find the issue in my code.
HTML CODE
<!DOCTYPE HTML>
<html>
<head>
<title>Webmaster's Top Secret Directory</title>
<link rel="stylesheet" href="index.css">
<script src="redirector5.js"></script>
</head>
<body background="camouflage.jpg" onload='write()'>
<div align="center">
<img src="header.png" alt="Warning"/>
</div><br><br><br><br><br><br>
<div id="container">
<form name="form1" onsubmit="return myFunction();">
<div><table align="center" class="table">
<tr><td>
<input type="text" class="inputtext2" name="text" value="open sesame" disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="identify yourself...." disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="omar saab" disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="verification step 1 of 4 passed.... enter secret phrase...." disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="i own you terminal. release security now and let me in" disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="verifying.... verification step 2 of 4 passed.... enter your purpose of entrance...." disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="manage personal files" disabled /></td>
</tr>
<tr>
<td><textarea class="inputtext2222" id='screen' disabled></textarea></td>
</tr>
<tr>
<td><textarea class="inputtext2222" id='screen2' disabled></textarea></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" id="myTextarea" autofocus spellcheck="false" /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
</table>
</div>
<input
type="submit"
name="submit">
</form>
</div>
</body>
</html>
JAVASCRIPT CODE
function myFunction() {
var x = document.getElementById("myTextarea").value;
if (x === "tango-whisky-70433863") {
document.location.href = "index6.html";
return false;
}
else {
alert('Command not found.\nYou are not supposed to be here.\nGet out now !');
return false;
}
}
function write(){
type();
type2();
}
var index = 0;
var text = 'verification 3 of 4 passed...';
function type()
{
document.getElementById('screen').innerHTML += text.charAt(index);
index += 1;
var t = setTimeout('type()',80);
}
var index = 0;
var text2 = 'enter serial number....';
function type2()
{
document.getElementById('screen2').innerHTML += text2.charAt(index);
index += 1;
var t = setTimeout('type2()',80);
}
NOTE When I call one of these 2 functions apart, it works.
I could be wrong, but I think that the issue is with index. You have the same variable name for each type, and when they run at the same time, it confuses the script. You have a variable named index, that will +=1, so when the next function gets it, it is messed up.
Try changing the variable for index on type2() to index2. See if this fixes it.
You have tried to declare the variable index twice. Try renaming it in the second function and it should work fine.
Explanation:
you declare var index = 0; twice within the same scope. in this case the second declaration is what gets used(fiddle example), and so there is only index variable inside the functions. That's why each function displays every second letter.

Javascript error while calculating

I have a php simple program to calculate a textbox with another textbox, 1 years ago, there's no problem after now, I have problem with my JavaScript. It can't count my textbox.
My form code is here (without html tag, to minimize code in here):
<table>
<tr>
<td>Tol</td>
<td>:</td>
<td><input type="text" maxlength="11" name="tol" onkeydown="calculate()" value="0" /></td>
</tr>
<tr>
<td>Parkir</td>
<td>:</td>
<td><input type="text" maxlength="11" name="parkir" onkeydown="calculate()" value="0" /></td>
</tr>
<tr>
<td>Joki</td>
<td>:</td>
<td><input type="number" maxlength="11" name="joki" onkeydown="calculate();" value="0" /></td>
</tr>
<tr>
<td>Other</td>
<td>:</td>
<td><input type="number" name="other" maxlength="11" onkeydown="calculate();" value="0" /> <input type="text" name="othername" maxlength="50" /> </td>
</tr>
<tr>
<td>Total</td>
<td>:</td>
<td><input type="text" id="subtotal" onfocus="this.value = numberFormat(this.value);" name="subtotal" maxlength="100" value="0" />
<input type="text" id="totalbox" name="totalbox" maxlength="100" />
</td>
</tr>
</table>
and my JS script:
function calculate(){
var num1=document.myform.tol.value;
var num2=document.myform.parkir.value;
var num3=document.myform.joki.value;
var num4=document.myform.other.value;
var sum=parseFloat(num1)+parseFloat(num2)+parseFloat(num3)+parseFloat(num4);
document.getElementById('totalbox').value=sum.toString();
document.getElementById('subtotal').value=sum.toString();
}
can somebody correct my code or is there any update from JS that made my JS code doesn't work now?
Try using the onkeyup event instead of onkeydown. The onkeydown event fires before the value of your textbox reflects the input being typed in.
Try referencing the input boxes by id rather than by form.name:
function calculate(){
var num1=document.getElementById('tol').value;
var num2=document.getElementById('parkir').value;
var num3=document.getElementById('joki').value;
var num4=document.getElementById('other').value;
var sum=parseFloat(num1)+parseFloat(num2)+parseFloat(num3)+parseFloat(num4);
document.getElementById('totalbox').value=sum.toString();
document.getElementById('subtotal').value=sum.toString();
}
add the id attribute to your inputs:
<input type="text" maxlength="11" name="tol" id="tol" onkeydown="calculate()" value="0" />
...
You might also want to make your code a little more robust by checking to see if the element exists before trying to get the value:
function calculate(){
var fld1 = document.getElementById('tol');
var num1 = 0;
if (fld1 && fld1 != 'undefined') num1 = fld1.value;
...

Categories

Resources