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;
Related
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>
I am stuck here with duch issue. There are 2 two entry boxes are for an amount and an interest rate (%).
If you click on the button, the page will show an overview of the balance until the amount have to be doubled.
Taking a simple numbers forexample 10 - is amount and 4 - is 4% intereste rate. So the result have to stop on amount of 20.
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = 1; i <= doubleS; i++) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
The issue is with your for loop bounds.
This will loop doubleX number of times: for (var i = 0; i < doubleX; i++)
This will loop until x surpasses doubleX: for (;x < doubleX;), which btw is better written with a while loop: while (x < doubleX)
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
result.innerHTML = '';
while (s < doubleS) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
Easiest way is to just use a for loop without the convoluted math with s in the middle:
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = s; i <= doubleS; i *= ((r / 100) + 1)) {
result.innerHTML += i + "<br>";
}
}
use a while loop and check is the value of s is bigger than or equal to doubleS
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
while(true) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
if(s >= doubleS){
break
}
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
function sum()
{
$(document).on('keyup', "*[data-field='unit'],*[data-field='unit_price']", function(e)
{
var unit = document.getElementById('unit').value;
var unitPrice = document.getElementById('unit_price').value;
var result = parseInt(unit) * parseInt(unitPrice);
if (!isNaN(result))
{
document.getElementById('amount').value = result;
}
});
}
p/s: this only function at normal form. but not dynamic form.
[edit ?]
$('#unit, #price').on('input',function()
{
let qty = parseInt($('#unit').val())
, price = parseFloat($('#price').val())
;
$('#amount').val((qty * price ? qty * price : 0).toFixed(2));
});
you can do this whit jQuery Plugin i write simple one
you can test it on this :
$.fn.sum = function(options) {
"use strict";
var self = this;
self.defaults = {
unit : '[data-field="unit"]',
unit_price : '[data-field="unit_price"]',
result : '[data-field="amount"]',
onCalculate : function(result){},
};
self.settings = $.extend({},self.defaults, options );
var unit_count = $(self).find('input'+self.settings.unit).length;
var unit_price_count = $(self).find('input'+self.settings.unit_price).length;
if(unit_count > 0 && unit_price_count > 0){
var unit, unit_price=0, result=0;
$($(self).find('input'+self.settings.unit_price)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
$($(self).find('input'+self.settings.unit)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
function sum(unit, unit_price){
var result = parseInt(unit) * parseInt(unit_price);
if (!isNaN(result)) {
return result;
}
}
}
}
$(document).ready(function(){
$('form').sum({
onCalculate: function(self, active, result){
$(active).closest('form').find(self.settings.result).val(result);
},
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="fff33">
<legend>
two
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit22">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price22">
<input type="text" data-field="amount" disabled>
</form>
<br>
<br><br>
<form id="fff">
<legend>
one
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price">
<input type="text" data-field="amount" disabled>
</form>
<br><br>
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 have 2 html textbox for users to enter numbers. To sum those numbers, I am passing the values to JavaScript variable and after addition displaying the result to html div section
<div class="input-left"><span><input class="textbox" id="left" name="count" type="text" size="5" value="" /></span></div>
<div class="input-right"><span><input class="textbox" id="right" name="count" type="text" size="5" value="" /></span></div>
<div id="result"> </div>
javascript:
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
But I have an issue with JavaScript. It not displaying the result. How to add both functions in same onkeyup function.
FIDDLE SETUP
Try this:
window.onload = function(){
var left = document.getElementById('left');
var right = document.getElementById('right');
var result = document.getElementById("result");
left.onkeyup = calc;
right.onkeyup = calc;
function calc() {
var a = parseFloat(left.value) || 0;
var b = parseFloat(right.value) || 0;
result.innerHTML = a + b ;
}
}
JSFiddle: http://fiddle.jshell.net/gYV8Z/3/
Update: To hide the result in case the sum equals zero , change the last line like this:
result.innerHTML = ( a + b ) || "";
JSFiddle: http://fiddle.jshell.net/gYV8Z/4/
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
it your code, var a is local variable. make it global variable.
but i would use this code.
function add(){
return parseFloat(document.getElementById('left').value) + parseFloat(document.getElementById('right').value);
}
document.getElementById('left').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}
document.getElementById('right').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}