I have some input with 3 values - entrance price, extra (in percent), price
It calculates by the formula: input price * per percentage extra = price
Here is my code:
HTML
function sum() {
var txtFirstNumberValue = document.getElementById('enterence_price').value;
var txtSecondNumberValue = document.getElementById('extra').value;
var result = parseFloat(txtFirstNumberValue) / 100 * parseFloat(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('price').value = result.toFixed(2);
}
}
<label>Enterence Price<br></label>
<input type="text" id="enterence_price" onkeyup="sum();">
<br>
<label>extra%<br></label>
<input type="text" id="extra" value="120%" onkeyup="sum();">
<br>
<label>Price<br></label>
<input type="text" id="price" onkeyup="sum();">
<br>
Now I need when I change the value in the "Price" input - my extra value should change automatically, the entrance price should not change
This is second formula:
Extra price =(price/entrance price)*100%
Pass the this keyword into your function, so you can detect which input has been triggered.
function sum(el) {
let entrPriceEl = document.getElementById('enterence_price');
let extraEl = document.getElementById('extra');
let priceEl = document.getElementById('price');
let result;
if (el.id === "enterence_price" || el.id === "extra") {
result = parseFloat(entrPriceEl.value) / 100 * parseFloat(extraEl.value);
if (!isNaN(result)) {
priceEl.value = result.toFixed(2);
}
} else if (el.id === "price") {
result = (priceEl.value / entrPriceEl.value) * 100;
if (!isNaN(result)) {
extraEl.value = result + "%";
}
}
}
<label>Enterence Price<br></label>
<input type="text" id="enterence_price" onkeyup="sum(this);">
<br>
<label>extra%<br></label>
<input type="text" id="extra" value="120%" onkeyup="sum(this);">
<br>
<label>Price<br></label>
<input type="text" id="price" onkeyup="sum(this);">
<br>
Related
I have three fields that are calculated: coef, cost of materials, and manufacturing cost.
First, calculate its coef * cost of materials, result in manufacturing cost input.
The calculation of the total amount is the cost of materials * manufacturing cost, but I need the ability to change the amount of Manufacturing cost and get the total result
How to do this?
My code:
function sum(el) {
let coefEl = document.getElementById('coef');
let entrPriceEl = document.getElementById('enterence_price');
let extraEl = document.getElementById('extra');
let priceEl = document.getElementById('price');
let extraresultEl;
let result;
if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
extraextraresultEl = parseFloat(coefEl.value) * parseFloat(entrPriceEl.value);
extraEl.value = extraextraresultEl;
result = (parseFloat(entrPriceEl.value) * parseFloat(coefEl.value) + parseFloat(extraEl.value));
if (!isNaN(result)) {
priceEl.value = result.toFixed(2);
}
} else if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
result = parseFloat(entrPriceEl.value) * parseFloat(extraEl.value);
if (!isNaN(result)) {
priceEl.value = result;
}
}
}
<label>Coefficient<br></label>
<input type="text" value="2" id="coef" onkeyup="sum(this);">
<br>
<label>The cost of materials<br></label>
<input type="text" value="2000" id="enterence_price" onkeyup="sum(this);">
<br>
<label>Manufacturing cost<br></label>
<input type="text" id="extra" onkeyup="sum(this);">
<br>
<label>Sum<br></label>
<input type="text" id="price" onkeyup="sum(this);">
<br>
You need to apply a different function on mf cost input, because if you will use the same function, it will never let you alter the value, because its value also getting generated from the same function you write for above 2 values
if you need something else, pls feel free to comment
let coefEl = document.getElementById('coef');
let entrPriceEl = document.getElementById('enterence_price');
let extraEl = document.getElementById('extra');
let priceEl = document.getElementById('price');
function sum(el) {
let extraresultEl;
if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
extraextraresultEl = parseFloat(coefEl.value) * parseFloat(entrPriceEl.value);
extraEl.value = extraextraresultEl;
result = (parseFloat(entrPriceEl.value) * parseFloat(coefEl.value) + parseFloat(extraEl.value));
if (!isNaN(result)) {
priceEl.value = result.toFixed(2);
}
} else if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
result = parseFloat(entrPriceEl.value) * parseFloat(extraEl.value);
if (!isNaN(result)) {
priceEl.value = result;
}
}
}
function canBeChnaged(el){
var coefVal = parseInt(coefEl.value);
var costofMatVal = parseInt(entrPriceEl.value);
var mfCostVal = parseInt(extraEl.value);
var finalSum = (coefVal * costofMatVal) + mfCostVal;
priceEl.value = finalSum.toFixed(2);
}
<label>Coefficient<br></label>
<input type="text" value="2" id="coef" onkeyup="sum(this);">
<br>
<label>The cost of materials<br></label>
<input type="text" value="2000" id="enterence_price" onkeyup="sum(this);">
<br>
<label>Manufacturing cost<br></label>
<input type="text" id="extra" onkeyup="canBeChnaged(this);">
<br>
<label>Sum<br></label>
<input type="text" id="price" onkeyup="sum(this);">
<br>
A more succinct way is to is to wrap everything into a <form> then listen for the input event. The input event will trigger a call to an event handler (in the example below it is function calc(e)) whenever the user enters data in a form control (in this case all <input>s of <form>). Use properties of HTML elements like type and step to control and validate user input. References to previously mentioned topics are located after the example below.
Details are commented in example below
// Register the <form>
const form = document.forms[0];
// Register all form controls of <form>
// In this case all <input> and <output>
const data = form.elements;
// Run function calc() if any valid user input is entered in <form>
form.oninput = calc;
// Pass the event
function calc(e) {
// Convert any valid user input of the <input>s into a real number
const c = parseFloat(data.cof.value);
const m = parseFloat(data.mat.value);
const l = parseFloat(data.lab.value);
// Reference the <output>
const s = data.sum;
// Realistic formula
const t = (c * m) + l;
// Display the value of output as the result of formula
s.value = t.toFixed(2);
}
:root,
input,
output {
font: 400 6vh/10vh Consolas;
}
label,
input,
output {
display: inline-block;
}
label {
width: 9ch;
}
input,
output {
height: 1.5ch;
width: 12ch;
text-align: right;
}
#cof {
width: 6ch;
text-align: center;
color: blue;
}
<form>
<label>Markup</label>
<input id="cof" type="number" value="2">
<br>
<label>Materials</label>
<input id='mat' type="number" value="0.00" step=".01">
<br>
<label>Labor</label>
<input id='lab' type="number" value='0.00' step=".01">
<hr>
<label>Total: </label>
<output id='sum'>0.00</output>
</form>
Reference
HTMLFormControlCollection
HTMLFormElement
<input> Element
I created a function that calculates the final cost of an order, and I'm trying to display it in a text box. However, the text box keeps returning "$ NaN" and I cannot find the error. I'm a very beginning student of html and js, so any explanation is appreciated.
function costCalculator() {
totalCost = (totalCost + burgerOnePrice * Number(burgerOne.value));
totalCost = (totalCost + burgerTwoPrice * Number(burgerTwo.value));
totalCost = (totalCost + burgerThreePrice * Number(burgerThree.value));
totalCost = totalCost * (1 + tip);
if (useCard == 1) {
if (Number(balance.value) >= totalCost) {
totalCost = 0;
cardBalance = cardBalance - totalCost;
balance.value = cardBalance;
finalCost.value = totalCost;
} else {
totalCost = (totalCost - Number(balance.value));
balance.value = 0;
finalCost.value = totalCost;
}
}
document.getElementById("finalCost").value= "$ "+parseFloat(this.totalCost).toFixed(2);
document.getElementById("balance").value= "$ "+parseFloat(this.balance).toFixed(2);
}
Here's the button that calls the function and the text box that I want it to appear it:
<button id="totalSales" onclick = "costCalculator();" >Calculate Total</button>
<br><br>
<input type="text" id="finalCost" value="" size="3" readonly="true" />
You should check console log or run debugger (F12) first - lot of bugs / missing info at least in question here, but in case I put something instead of all missing items, it starts to run without code errors at least ;-)
var burgerOnePrice = 123,
burgerTwoPrice = 234,
burgerThreePrice = 345,
tip = 456,
useCard = 1;
function costCalculator() {
var totalCost = 0,
f = document.forms[0],
balance = { value: f.balance.value.replace(/[$ ]/,'') },
burgerOne = f.burgerOne,
burgerTwo = f.burgerTwo,
burgerThree = f.burgerThree;
totalCost = (totalCost + burgerOnePrice * Number(burgerOne.value));
totalCost = (totalCost + burgerTwoPrice * Number(burgerTwo.value));
totalCost = (totalCost + burgerThreePrice * Number(burgerThree.value));
totalCost = totalCost * (1 + tip);
if (useCard == 1) {
if (Number(balance.value) >= totalCost) {
totalCost = 0;
cardBalance = cardBalance - totalCost;
balance.value = cardBalance;
f.finalCost.value = totalCost;
} else {
totalCost = (totalCost - Number(balance.value));
balance.value = 0;
f.finalCost.value = totalCost;
}
}
document.getElementById("finalCost").value = "$ " + parseFloat(totalCost).toFixed(2);
document.getElementById("balance").value = "$ " + parseFloat(balance.value).toFixed(2);
}
<form>
<input type="button" id="totalSales" onclick = "costCalculator();" value="Calculate Total">
<br><br>
<input name="burgerOne" value="1">
<input name="burgerTwo" value="2">
<input name="burgerThree" value="3">
<input type="text" id="finalCost" value="" size="3" readonly="true" />
<input id="balance" value="$ 100000">
</form>
I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>
I have written a code to calculate Burger, Coca and Salad price. The code should return a number (or a factor) based on the number or each ordered item. I can't figure out which part of the code is not right. it doesn't work when I change the number of items.
var BurgNum = document.getElementById('Bnum').value,
CocNum = document.getElementById('Cnum').value,
SalNum = document.getElementById('Snum').value,
Totalprice;
function getValue(n) {
return n >= 2 && n < 5 ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
}
var XBurgNum = getValue(BurgNum);
var XCocNum = getValue(CocNum);
var XSalNum = getValue(SalNum);
Totalprice = XBurgNum * 10 + XCocNum * 5 + XSalNum * 4
document.getElementById('price').value = Totalprice;
<html>
How many Burgers you want to order? <input type="number" id="Bnum" value="0" onchange="getValue(n);"></input>
<br> How many Cocas you want to order? <input type="number" id="Cnum" value="0" onchange="getValue(n);"></input>
<br> How many Salads you want to order? <input type="number" id="Snum" value="0" onchange="getValue(n);"></input>
<br> Price: <input type="number" id="price" readonly="readonly"></input>
</html>
You are calling a function onchange which returns a value, but does nothing with it. Instead, your onchange function can get the values needed for the calculation and update the price accordingly.
var burg = document.getElementById('Bnum'),
coc = document.getElementById('Cnum'),
sal = document.getElementById('Snum'),
totalPrice = 0;
document.getElementById('price').value = totalPrice;
var updatePrice = function() {
var burgNum = burg.value,
cocNum = coc.value,
salNum = sal.value;
var xNums = [];
[burgNum, cocNum, salNum].forEach(function(n, i) {
xNums[i] = (n >= 2 && n < 5) ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
});
totalPrice = xNums[0]*10 + xNums[1]*5 + xNums[2]*4;
document.getElementById('price').value = totalPrice;
}
How many Burgers do you want to order?
<input type="number" id="Bnum" value ="0" onchange="updatePrice()"/><br>
How many Cocas do you want to order?
<input type="number" id="Cnum" value ="0" onchange="updatePrice()"/><br>
How many Salads do you want to order?
<input type="number" id="Snum" value="0" onchange="updatePrice()"/><br>
Price:
<input type="number" id="price" readonly="readonly"/>
That is because you are not calling right statement on 'onchange' event. You just call the getVAlue(n) function which does nothing except return a value that you also use for
var XBurgNum = getValue(BurgNum);
var XCocNum = getValue(CocNum);
var XSalNum = getValue(SalNum);
But you are not updating the output on change event.
Try this, It will help you...
function getValue(val)
{
var BurgNum = parseInt(document.getElementById('Bnum').value);
var CocNum = parseInt(document.getElementById('Cnum').value);
var SalNum = parseInt(document.getElementById('Snum').value);
BurgNum = (BurgNum>=2 && BurgNum<5)?BurgNum*0.9:(BurgNum<2)?BurgNum:BurgNum-1;
CocNum = (CocNum>=2 && CocNum<5)?CocNum*0.9:(CocNum<2)?CocNum:CocNum-1;
SalNum = (SalNum>=2 && SalNum<5)?SalNum*0.9:(SalNum<2)?SalNum:SalNum-1;
Totalprice = BurgNum*10 + CocNum*5 + SalNum*4;
document.getElementById('price').value = (Totalprice>0 && Totalprice!=='NaN')?Totalprice:0;
}
<html>
How many Burgers you want to order? <input type="number" id="Bnum" value ="0" onChange="getValue(this.value);"></input>
<br>
How many Cocas you want to order? <input type="number" id="Cnum" value ="0" onChange="getValue(this.value);"></input>
<br>
How many Salads you want to order? <input type="number" id="Snum" value="0" onChange="getValue(this.value);"></input>
<br>
Price: <input id="price" readonly="readonly"></input>
</html>
Happy Coding...
How can i operate 2 math operation inside jquery ?
result = val;
a = result * 5000;
b = result * 0.1;
result = a + b;
https://jsfiddle.net/7ugdjezb/
my codes didn't give the right result
function calculate() {
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
var price = $('#price').val();
if (rege.test(price)) {
val = parseInt(price);
var result = val;
if ($('input[name="selectedItems1"]').is(":checked")) {
a = (result * 5000);
b = result * 0.1;
result = a + b;
} else {
result = result * 5000;
}
if (isNaN(result))
j.value = 0
else
j.value = result;
} else
alert("Error in input");
}
$(function() {
$('input[name="selectedItems1"]').change(function() {
calculate();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form>
<input type="text" class="form-control" placeholder="Item Price" id="price" onkeyup="calculate()" />
<br />
<input type="checkbox" name="selectedItems1" value="val1" />Tax 10%
<br/>
<input type="text" id="output" value="Output" />
</form>
Here is a cleaned up version. Please note the
result += (result * 0.1); part
function calculate() {
var $outPut = $("#output"),
rege = /^[0-9]*$/,
price = $('#price').val() || 0,
result = 0;
if (!rege.test(price)) {
console.log("Error in input");
} else {
result = parseInt(price) * 5000;
if ($('input[name="selectedItems1"]').is(":checked")) {
result += (result * 0.1);
}
}
$outPut.val(result.toFixed(2));
}
$(function() {
$('#price').on("keyup",calculate);
$('input[name="selectedItems1"]').on("change",calculate);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" class="form-control" placeholder="Item Price" id="price" />
<br />
<input type="checkbox" name="selectedItems1" value="val1" />Tax 10%
<br/>
<input type="text" id="output" value="Output" />
</form>
Everything is good in jsfiddle, its just you are doing wrong calculation in it. I'm assuming you want to find 10% of number you write in textfield.
If yes, the here you're doing it wrong
result = a + b;
Just replace above line with this in your fiddle and it'll work.
result = b;
This:
a = (result * 5000);
b = result * 0.1;
result = a + b;
should be:
a = (result * 5000);
b = a * 0.1; // calculate 10% of (result * 5000) not result
result = a + b;
or in one line like this:
result *= (5000 * 1.1);
Try using bodmas, brackets over division over multiplication over addition over subtraction.
results = (result * 5000) + result * 0.1;