RealTime Calculations based on inputs and clicked radio buttons - javascript

I want to create a real time calculator for Net-Profit based on the trasaction, of the given quantity at given buy and sell price and it has 2 radio buttons as inputs.
What is happening is, I have to hit enter after putting values and selecting the button.
Where as what I want is, as soon as I input values and select radio button it should calculate the values.
Pl help me correct my code.
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Brokerage Calculator</title>
<head>
<script src="jquery-min.js"></script>
</head>
<body>
Buy Price
<input type="number" min="0" id="bp"><br />
Sell Price
<input type="number" min="0" id="sp"><br />
Qty:
<input type="number" min="0" id="qty"><br />
NSE:
<input name="exchname" id="nse" value="0.0000325" type="radio" checked="checked"><br />
BSE:
<input name="exchname" id="bse" value="0.0000275" type="radio"><br />
Turnover:
<span id="turnover">0</span><br />
Brokerage:
<span id="brokerage">0</span><br />
Security Transction Tax:
<span id="stt">0</span><br />
Total Tran Charges:
<span id="ttc">0</span><br />
SEBI Charges:
<span id="sebi">0</span><br />
Service Tax:
<span id="servtax">0</span><br />
Stamp Duty:
<span id="std">0</span><br />
Total Brokerage + Taxes:
<span id="ttx">0</span><br />
Net Profit:
<span id="pnl">0</span><br />
<script>
$('input').keyup(function(){ // run anytime the value changes
var buyPrice = parseFloat($('#bp').val()); // get value of field
var sellPrice = parseFloat($('#sp').val()); // convert it to a float
var quantity = parseFloat($('#qty').val());
var turnoverValue = (buyPrice + sellPrice) * quantity;
var sttValue = sellPrice * quantity * 0.025 / 100;
var sebiValue = turnoverValue * 0.0002 / 100;
var stdValue = 0.00002 * turnoverValue;
var excrate = document.querySelector('input[name="exchname"]:checked').value;
if(buyPrice<166.67){
var brkgbp = 0.05;
} else {
var brkgbp = buyPrice * 0.03 / 100;
}
if(sellPrice<166.67){
var brkgsp = 0.05;
} else {
var brkgsp = sellPrice * 0.03 / 100;
}
var brokerageValue = (brkgbp + brkgsp) * quantity;
var ttcValue = excrate * turnoverValue;
var servtaxValue = (brokerageValue + ttcValue + sebiValue) * 15 / 100;
var ttxValue = brokerageValue + sttValue + ttcValue + sebiValue + servtaxValue + stdValue;
var pnlValue = ((sellPrice - buyPrice) * quantity) - ttxValue;
$('#turnover').html(turnoverValue.toFixed(2));
$('#brokerage').html(brokerageValue.toFixed(2));
$('#stt').html(sttValue.toFixed(2));
$('#sebi').html(sebiValue.toFixed(2));
$('#servtax').html(servtaxValue.toFixed(2));
$('#ttc').html(ttcValue.toFixed(2));
$('#std').html(stdValue.toFixed(2));
$('#ttx').html(ttxValue.toFixed(2));
$('#pnl').html(pnlValue.toFixed(2));
});
<script>
</body>
</html>

Your closing script tag is missing the /, i.e. </script>
For your inputs, you're checking for the release of a keyboard key, which wouldn't fire for clicking radio buttons. Since you're checking to see if the value of the input has changed, you should change $('input').keyup to $('input').change.
edit: of course, you should do the NaN checking as well, as the other answers indicated - but the problem you described is solved by using the change event.

Didn't you forgot to close the script tag?
<script> ... </script>
Also, use
var buyPrice = parseFloat($('#bp').val()) || 0;
to initialize with a default value, so you don't get NaN
If you want the values to change when you reselect an option in the radio buttons, use:
function calculate(){ // run anytime the value changes
....
}
$('input').on('keyup', calculate);
$('input').on('click', calculate);
EDIT: I made a JSfiddle
https://jsfiddle.net/v3qd7b26/

Multiple issue in your code
1. You are missing the / in the script tag at the end. It should be </script> instead of <script>.
2. You need to ensure that the values entered are valid numbers only and then only proceed further, you can validate that using isNaN function in javascript
if(!isNaN(buyPrice) && !isNaN(sellPrice) && !isNaN(quantity)){
3.
Also, for checkbox need to add another selector. So you can create a common function and call it.
$("input").keyup(calculate);
$("input:checked").keyup(calculate);
Complete code:
$("input").keyup(calculate);
$("input:checked").keyup(calculate);
function calculate(){ // run anytime the value changes
var buyPrice = parseFloat($('#bp').val()); // get value of field
var sellPrice = parseFloat($('#sp').val()); // convert it to a float
var quantity = parseFloat($('#qty').val());
if(!isNaN(buyPrice) && !isNaN(sellPrice) && !isNaN(quantity)){
var turnoverValue = (buyPrice + sellPrice) * quantity;
var sttValue = sellPrice * quantity * 0.025 / 100;
var sebiValue = turnoverValue * 0.0002 / 100;
var stdValue = 0.00002 * turnoverValue;
var excrate = document.querySelector('input[name="exchname"]:checked').value;
if(buyPrice<166.67){
var brkgbp = 0.05;
} else {
var brkgbp = buyPrice * 0.03 / 100;
}
if(sellPrice<166.67){
var brkgsp = 0.05;
} else {
var brkgsp = sellPrice * 0.03 / 100;
}
var brokerageValue = (brkgbp + brkgsp) * quantity;
var ttcValue = excrate * turnoverValue;
var servtaxValue = (brokerageValue + ttcValue + sebiValue) * 15 / 100;
var ttxValue = brokerageValue + sttValue + ttcValue + sebiValue + servtaxValue + stdValue;
var pnlValue = ((sellPrice - buyPrice) * quantity) - ttxValue;
$('#turnover').html(turnoverValue.toFixed(2));
$('#brokerage').html(brokerageValue.toFixed(2));
$('#stt').html(sttValue.toFixed(2));
$('#sebi').html(sebiValue.toFixed(2));
$('#servtax').html(servtaxValue.toFixed(2));
$('#ttc').html(ttcValue.toFixed(2));
$('#std').html(stdValue.toFixed(2));
$('#ttx').html(ttxValue.toFixed(2));
$('#pnl').html(pnlValue.toFixed(2));
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Buy Price
<input type="number" min="0" id="bp"><br />
Sell Price
<input type="number" min="0" id="sp"><br />
Qty:
<input type="number" min="0" id="qty"><br />
NSE:
<input name="exchname" id="nse" value="0.0000325" type="radio" checked="checked"><br />
BSE:
<input name="exchname" id="bse" value="0.0000275" type="radio"><br />
Turnover:
<span id="turnover">0</span><br />
Brokerage:
<span id="brokerage">0</span><br />
Security Transction Tax:
<span id="stt">0</span><br />
Total Tran Charges:
<span id="ttc">0</span><br />
SEBI Charges:
<span id="sebi">0</span><br />
Service Tax:
<span id="servtax">0</span><br />
Stamp Duty:
<span id="std">0</span><br />
Total Brokerage + Taxes:
<span id="ttx">0</span><br />
Net Profit:
<span id="pnl">0</span><br />

Related

Run javascript with value of field onload

Trying to have script run on page load with value of input on page load. The script runs onchange fine but I also want to run on page load. I have tried onload="calculateAmount(this.value);">
<input type="number" name="tot_pin_requested" id="tot_pin_requested" class="inputbox autowidth" value="{{ PPDEFAULT_VALUE }}" onchange="calculateAmount(this.value);">
<script>
function calculateAmount(val) {
var price = val * 1;
//display the result
var tot_price = price + (price * 0.029 + .30);
tot_price.toFixed(2);
var divobj = document.getElementById('amount');
divobj.value = tot_price;
}
</script>
Don't add it to the element, just have it separate:
<script>calculateAmount(document.querySelector("#tot_pin_requested").value);</script>
If you want to be sure the document is ready just use DOMContentLoaded event.
Also i suggest you use parseFloat on the inputValue so it's correctly changed from type string to type number. ( or parseInt(value, radix) if you will have just int values )
Also i don't know what is the logic behind var price = val * 1....
See below
window.addEventListener('DOMContentLoaded', (event) => {
const inputValue = document.getElementById('tot_pin_requested').value
calculateAmount(parseFloat(inputValue))
})
function calculateAmount(val) {
var price = val * 1;
//display the result
var tot_price = price + (price * 0.029 + .30);
tot_price.toFixed(2);
var divobj = document.getElementById('amount');
divobj.value = tot_price;
}
<input type="number" name="tot_pin_requested" id="tot_pin_requested" class="inputbox autowidth" value="10" onchange="calculateAmount(this.value);">
<input type="number" id="amount">

How to engage different function on different select

That's my second script ever. I'm learning basics at the same time. I would like to engage different function on different option selected.
I try to give value to different option to use it later where the switch is.
It says cannot set property of null. If someone could explain me what I'm doing wrong it would be amazing. Please forgive me for silly mistakes, 3 days of learning in total, unfortunately theory doesn't work on me if i will not try it.
<html>
<body>
<div>
<h2> Daily calorie intake</h2>
<input type = "number" placeholder = "your height" id = "height" min = "1" max = "230"><p></p>
<input type = "number" placeholder = "your age" id = "age" min = "1" max = "120"><p></p>
<input type = "number" placeholder = "your weight" id = "weight" min = "1" max = "500"><p></p>
Your sex
<select name = "sex" id = "sex">
<option value = "1" id = "male">male</option>
<option value = "2" id = "female">female</select><p></p>
<button onclick="calculate()">Calculate</button>
</div>
<script>
var height = document.getElementById('height').onclick;
var age = document.getElementById('age').onclick;
var weight = document.getElementById('weight').onclick;
var sex = 1;
function calculate(height, age, weight, sex) {
switch(sex) {
case sex: 1
calculate = 66.5 * (13.75 * weight) + (5 * height) - (6.76 * age)
case sex: 2
calculate = 655.1 * (9.56 * weight) + (1.85 * height) - (4.68 * age)
break;
default: 1
}
document.getElementById('calculate').innerHTML = calculate
}
</script>
</body>
</html>
The error Uncaught TypeError: Cannot set property 'innerHTML' of null means that the object that you are calling .innerHTML on doesn't exist. In your case that's this line:
document.getElementById('calculate').innerHTML = calculate
and you get that error because you don't have an element with an id of calculate. If you don't have that element, you can't call .innerHTML on it.
You also need to get the data out of your form fields with the .value property, not the onclick property.
See additional comments below:
<html>
<head>
<title>Sample Page</title>
<style>
div { margin:1em; } /* adds vertical space before and after each div */
</style>
</head>
<body>
<div>
<!-- You can't have an <h2> if you don't already have an <h1> for it to be
a sub-section of. Don't use HTML elements because of how they style the output.
Use CSS to style. Also, don't use <p></p> to create vertical space. Again, use
CSS for style. -->
<h1> Daily calorie intake</h1>
<div><input type="number" placeholder="your height" id="height" min="1" max="230"></div>
<div><input type="number" placeholder="your age" id="age" min="1" max="120"></div>
<div><input type="number" placeholder="your weight" id="weight" min="1" max="500"></div>
<div>Your sex
<select id="sex">
<option value="1" id="male">male</option>
<option value="2" id="female">female</option>
</select>
</div>
<button>Calculate</button>
</div>
<div id="output"></div>
<script>
// Do your event binding in JavaScript, not in HTML
document.querySelector("button").addEventListener("click", calculate);
// Get references to the elements you'll need (not the value of their onclick properties)
var height = document.getElementById('height');
var age = document.getElementById('age');
var weight = document.getElementById('weight');
var sex = 1;
// You don't need any arguments because you already have references to the fields
// where the data is.
function calculate() {
// Declare the variable the will hold the result and don't use the
// name of the function as the name of the variable
let result = null;
switch(sex) {
// To get the data out of a form field, you must access its .value property
case sex: 1
result = 66.5 * (13.75 * weight.value) + (5 * height.value) - (6.76 * age.value);
break;
case sex: 2
result = 655.1 * (9.56 * weight.value) + (1.85 * height.value) - (4.68 * age.value);
break;
default: 1
}
// Make sure you reference elements that exist and don't use
// .innerHTML when there is no HTML in the string.
document.getElementById('output').textContent = result;
}
</script>
</body>
</html>
I hope this helps, this code is working
var height = document.getElementById('height');
var age = document.getElementById('age');
var weight = document.getElementById('weight');
var boton = document.getElementById('boton');
function calculate(height, age, weight, sex) {
switch(sex) {
case 1:
var calculo = 66.5 * (13.75 * weight) + (5 * height) - (6.76 * age);
break;
case 2:
var calculo = 655.1 * (9.56 * weight) + (1.85 * height) - (4.68 * age);
break;
default: 1
}
console.log(calculo);
return calculo;
}
boton.addEventListener('click', () => calculate(height.value, age.value, weight.value, 1));
<button id="boton"> Click me </button>
<input type = "number" placeholder = "your height" id = "height" min = "1" max = "230"/>
<input type = "number" placeholder = "your age" id = "age" min = "1" max = "120"/>
<input type = "number" placeholder = "your weight" id = "weight" min = "1" max = "500"/>

How to calculating time difference

I'm trying to make a program where i put in to different times and get the difference in minute after clicking the "calculate" button. I'm not sure if my approach is correct, there may be some typo's.
I'v tried to make the different input values to number but it seems like there is another underlying problem which I can't see.
var hour1=document.getElementById("hour1");
var min1=document.getElementById("min1");
var hour2=document.getElementById("hour2");
var min2=document.getElementById("min2");
function calc(){
var minutt1=Number(hour1)*60+Number(min1);
var minutt2=Number(hour2)*60+Number(min2);
var resultat=0;
resultat = Number(minutt1) - Number(minutt2);
document.getElementById("result").innerHTML="Time differance is:" + Number(resultat);
}
<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min1">
<button type="button" onclick="calc()">Regn ut</button>
<div id="result"></div>
I expect getting a number which represents the time difference in minutes, but the actual output is "NaN".
You need to get the value of hour1, min1, hour2, and min2. You also don't have an element min2:
var hour1=document.getElementById("hour1").value;
var min1=document.getElementById("min1").value;
var hour2=document.getElementById("hour2").value;
var min2=document.getElementById("min2").value;
What your code was trying to do was multiply and subtract HTML elements (never a good idea).
var hour1 = document.getElementById("hour1").value;
var min1 = document.getElementById("min1").value;
var hour2 = document.getElementById("hour2").value;
var min2 = document.getElementById("min2").value;
function calc() {
var minutt1 = Number(hour1) * 60 + Number(min1);
var minutt2 = Number(hour2) * 60 + Number(min2);
var resultat = 0;
resultat = Number(minutt1) - Number(minutt2);
document.getElementById("result").innerHTML = "Time differance is:" + Number(resultat);
}
<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>
<div id="result"></div>
Other answers are close, but you need to get the value of the inputs after you click the button
var hour1 = document.getElementById("hour1");
var min1 = document.getElementById("min1");
var hour2 = document.getElementById("hour2");
var min2 = document.getElementById("min2");
window.calc = function () {
var minutt1 = parseInt(hour1.value) * 60 + parseInt(min1.value);
var minutt2 = parseInt(hour2.value) * 60 + parseInt(min2.value);
var resultat = minutt1 - minutt2;
document.getElementById("result").innerHTML = "Time differance is:" + resultat;
console.log({minutt1:minutt1,minutt2:minutt2,resultat:resultat,
hour1:hour1,min1:min1,
hour2:hour2,min2:min2
})
};
<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>
<div id="result"></div>

Total price calculator logic difficulty

I have two number inputs, what I want to do is to get dynamially the total price.
The problem is that when I decrease the number its still adding and doesn't work correctly. Actually my brain cannot imagine any way to code it correctly. Could someone give me any clue please?
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<script>
var vipPrice = 290;
var openPrice = 80;
var totalPrice = 0
$('#open').on("change", function() {
totalPrice = totalPrice + ($("#open").val() * openPrice);
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function() {
totalPrice = totalPrice + ($("#vip").val() * vipPrice);
$("#doZaplaty").html(totalPrice);
});
</script>
Because totalPrice = totalPrice + ($("#open").val() * openPrice); will add up previous result, as I commented.
However, you have 2 different total to take into account, so it's not easy to keep the state with only one total, because you need to subtract the previous result ,or calculate the change from previous value.
Instead, you can have 2 different total, like openTotal for result on #open and vipTotal on result for #vip, then you can use openTotal = ($("#open").val() * openPrice); to get the current state. And when you need to output the result, use $("#doZaplaty").html(openTotal + vipTotal); to show the final total.
var vipPrice = 290;
var openPrice = 80;
var openTotal = 0;
var vipTotal = 0;
$('#open').on("change", function() {
// As the totals are separated, we just need to get its current values computed.
openTotal = ($("#open").val() * openPrice);
$("#doZaplaty").html(openTotal + vipTotal);
});
$('#vip').on("change", function() {
vipTotal = ($("#vip").val() * vipPrice);
$("#doZaplaty").html(openTotal + vipTotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
Because you always add to totalPrice. Try this instead (untested):
<script>
var totalPrice = 0
function GetTotalPrice(vipNum,openNum){
var vipPrice = 290;
var openPrice = 80;
var total = vipNum * vipPrice + openNum * openPrice;
return total;
}
$('#open').on("change", function(){
totalPrice = GetTotalPrice($("#vip").val(),$("#open").val());
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function(){
totalPrice = GetTotalPrice($("#vip").val(),$("#open").val());
$("#doZaplaty").html(totalPrice);
});
</script>
Please tyr by this simple way
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
Set 2 hidden fields to store temp calculation value
<input type="hidden" name="totalPriceopenTemp" id='totalPriceopenTemp' value="0">
<input type="hidden" name="totalPricevipTemp" id='totalPricevipTemp' value="0">
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<script>
var vipPrice = 290;
var openPrice = 80;
var totalPrice = 0;
var totalPriceopenTemp = 0;
var totalPricevipTemp = 0;
$('#open').on("change", function() {
totalPriceopenTemp = ($("#open").val() * openPrice);
$("#totalPriceopenTemp").val(totalPriceopenTemp);
totalPrice = parseInt($("#totalPriceopenTemp").val())+parseInt($("#totalPricevipTemp").val());
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function() {
totalPricevipTemp = ($("#vip").val() * vipPrice);
$("#totalPricevipTemp").val(totalPricevipTemp);
totalPrice = parseInt($("#totalPriceopenTemp").val())+parseInt($("#totalPricevipTemp").val());
$("#doZaplaty").html(totalPrice);
});
</script>
I think It will work for you

Using toFixed in the right place

I have a form which outputs a calculation from an input field and a drop down.
The script is fine apart from the grand total. When you type in a figure and select a value from the drop down, the grand total is rounded to 2 decimal places in the html.
Can anyone see why this is happening?
The form is below:
<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
<option value="1.50">Fast</option>
<option value="2.50">Medium</option>
<option value="3.50">Slow</option>
</select>
The javascript is below:
function updateCost()
{
var amount = parseFloat($('#amount').val()).toFixed(2);
var delivery = parseFloat($('#delivery').val()).toFixed(2);
var total = parseFloat(amount) + parseFloat(delivery);
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
var fixedrate = parseFloat(total / 100 * 8.2).toFixed(2);
var grandtotal = parseFloat(fixedrate) + parseFloat(total);
$("#grandtotal").html(grandtotal);
$("#total").html(total);
$("#fixedrate").html(fixedrate);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
$('#grandtotal').change(function(){ updateCost(); });
});
toFixed(2) should only be used in the part of the code that outputs it. In this case, you should have constructs like $("#someID").html(total.toFixed(2)), and remove the extra parseFloat()s. Something like this:
function updateCost() {
var amount = parseFloat(document.getElementById("amount").value),
delivery = parseFloat(document.getElementById("delivery").value),
total = amount + delivery,
fixedrate = total / 100 * 8.2,
grandtotal = fixedrate + total;
document.getElementById("total").innerHTML = total.toFixed(2);
document.getElementById("amountdiv").innerHTML = amount.toFixed(2);
document.getElementById("deliverydiv").innerHTML = delivery.toFixed(2);
document.getElementById("grandtotal").innerHTML = grandtotal.toFixed(2);
document.getElementById("fixedrate").innerHTML = fixedrate.toFixed(2);
}
$(function(){
document.getElementById("amount").onchange =
document.getElementById("delivery").onchange = updateCost;
});

Categories