Currently I am working in a Bitcoin live price project with jquery. Now I need to develop a live price difference percentage change calculator. Calculator is working fine. But not working automatically when Bitcoin live price changing. I need to edit in input. Keyup event needed for working. I need to make it as always automatically. Please make it as automatically without keyup.. I created a Codepen page for it. https://codepen.io/toolsim/pen/Rwywjap . My codes;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="text" id="btc-price" class="main01 dz-none from01 for-copy01 input bldo te-cen" value="">
<input type="text" value="25000" class="main02 percentagez to01 input bldo te-cen">
<input type="text" class="rz-result result01 input bldo te-cen">
<script type="text/javascript">
$(document).on("change keyup blur", ".main02", function() {
var first = Number($('.from01').val());
var second = Number($('.to01').val());
var minus = second - first; // 2000 - 1000 = {1000 = minus}
var divide = (minus / first); // 1000 / 1000 = 1
var multiply = divide * 100; // 1 * 100 = 100%
$('.result01').val(Number(multiply).toFixed(2));
});
</script>
<script type="text/javascript">
let weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade');
let stockPriceInput = document.querySelector('#btc-price');
let lastPrice = null;
weburl.onmessage = (event) => {
let stockObject = JSON.parse(event.data);
let price = parseFloat(stockObject.p).toFixed(2);
stockPriceInput.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
stockPriceInput.value = price;
lastPrice = price;
};
</script>
maybe like this:
function set_bts(_price){
$('.main01').val(_price);
var first = Number($('.from01').val());
var second = Number($('.to01').val());
var minus = second - first; // 2000 - 1000 = {1000 = minus}
var divide = (minus / first); // 1000 / 1000 = 1
var multiply = divide * 100; // 1 * 100 = 100%
$('.result01').val(Number(multiply).toFixed(2));
}
var weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade');
weburl.onmessage = function(event){
var stockObject = JSON.parse(event.data);
var price = parseFloat(stockObject.p).toFixed(2);
set_bts(price)
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="text" id="btc-price" class="main01 from01" value="">
<input type="text" value="25000" class="to01">
<input type="text" class="result01">
Related
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">
So I have this form that is performing very basic calculations and when I submit it, it results to NaN.
The thing that is confusing me is when I do a typeof of one of the variables assigned to the value of each input, it returns "number", and yet I get NaN as a result. Can anyone tell me why or what it is I am doing wrong?
Here's my HTML:
<form name="baddiesCost">
<input type="number" placeholder="Total Caught" name="goomba" id="goomba-form">
<input type="number" placeholder="Total Caught" name="bobombs" id="bob-ombs-form">
<input type="number" placeholder="Total Caught" name="cheepCheeps" id="cheep-form">
<button id="submitForm">Submit</button>
</form>
<h1 id="total"></h1>
Here's my JavaScript:
document.baddiesCost.addEventListener("submit", function(e) {
e.preventDefault();
var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
var goombaCost = 5;
var bobombsCost = 7;
var cheepCost = 11;
var showTotal = document.getElementById("total");
var total = goombaCaught + bobombsCaught + cheepsCaught;
showTotal.textContent = cheepsCaught;
console.log(bobombsCaught);
console.log(typeof bobombsCaught);
})
This statement document.baddiesCost.bobombs.value * bobombsCost; uses variable bobombsCost which is not defined at this time.
So, it is similar to: document.baddiesCost.bobombs.value * undefined; which will be NaN.
To solve this put variable inicialization before usage like in following code:
document.baddiesCost.addEventListener("submit", function(e) {
e.preventDefault();
var goombaCost = 5;
var bobombsCost = 7;
var cheepCost = 11;
var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
var showTotal = document.getElementById("total");
var total = goombaCaught + bobombsCaught + cheepsCaught;
showTotal.textContent = cheepsCaught;
console.log(bobombsCaught);
console.log(typeof bobombsCaught);
})
Anyway, NaN is number type, you can refer to following post for more explaination.
I am completing the 57 programming exercises book by Brian P. Hogan.
With most of these exercises, I've tried to develop a GUI.
In the following exercise, I want to calculate the Simple Interest of a Principal value over a period of years. Simply put:
var yearlyInterest = Principal * (Percentage(whole number) /= 100)
(yearlyInterest * numberOfYears) + Principal
// outputs total amount at the end of investment over a period of however many years
As you can see in the example above, there are three core inputs - Principal, Percentage and Time.
When creating the graphical user interface, I am struggling to get all of these core inputs to calculate the result simultaneously.
The following code only manages to calculate the result once I enter the number for the Time input. (excuse my poor coding skills i.e. global variables, I'm only up to exercise 12!)
HTML
<!DOCTYPE html>
<html lang="en">
<body>
<label for="principal">Principal</label>
<input type="number" class="principal" style="border-color: black;">
<label for="percentage">Percentage</label>
<input type="number" class="percentage" style="border-color: black;">
<label for="time">Time</label>
<input type="number" class="time" style="border-color: black;">
<div id="result"></div>
</body>
<script src="simpleInterest.js"></script>
</html>
JS
var principal = document.getElementsByClassName("principal");
var percentage = document.getElementsByClassName("percentage");
var time = document.getElementsByClassName("time");
var output = document.querySelector("#result");
var result;
var newResult;
var finalOutput;
document.addEventListener('input', function (event) {
if ( event.target.classList.contains( 'principal' ) ) {
var newPrincipal = principal[0].value;
result = newPrincipal;
}
if ( event.target.classList.contains( 'percentage' ) ) {
var newPercentage = percentage[0].value;
newResult = result * (newPercentage / 100);
}
if ( event.target.classList.contains( 'time' ) ) {
var newTime = time[0].value;
finalOutput = (newResult * newTime) + Number(result);
}
output.innerHTML = `${finalOutput ? finalOutput : ""}`
}, false);
Could somebody please show me an effective way to simultaneously calculate something based on each input event and output it using the .innerHTML method?
Thanks!
You need to get the values of all the inputs, not just the one that the user is currently typing in. Define a single function that does this, and add it as an event listener for all 3 inputs.
var principal = document.querySelector(".principal");
var percentage = document.querySelector(".percentage");
var time = document.querySelector(".time");
var output = document.querySelector("#result");
function calcInterest() {
var newPrincipal = parseFloat(principal.value);
var newPercentage = parseFloat(percentage.value);
var newTime = parseFloat(time.value);
if (!isNaN(newPrincipal) && !isNaN(newPercentage) && !isNaN(newTime)) {
var result = newPrincipal + newTime * newPrincipal * newPercentage / 100;
output.textContent = result;
}
}
principal.addEventListener("input", calcInterest);
percentage.addEventListener("input", calcInterest);
time.addEventListener("input", calcInterest);
<label for="principal">Principal</label>
<input type="number" class="principal" style="border-color: black;"><br>
<label for="percentage">Percentage</label>
<input type="number" class="percentage" style="border-color: black;"><br>
<label for="time">Time</label>
<input type="number" class="time" style="border-color: black;"><br> Result:
<div id="result"></div>
Create function to calculate, and call this function instead of just executing some code. Something like that:
var principal = document.getElementsByClassName("principal")
var percentage = document.getElementsByClassName("percentage")
var time = document.getElementsByClassName("time")
var output = document.querySelector("#result")
var result
var newResult
var finalOutput
var calculate = () => {
var newPrincipal = principal[0].value;
result = newPrincipal
var newPercentage = percentage[0].value
newResult = result * (newPercentage / 100)
var newTime = time[0].value
finalOutput = (newResult * newTime) + Number(result)
}
document.addEventListener('input', function (event) {
if ( event.target.classList.contains( 'principal' ) ) {
calculate();
}
if ( event.target.classList.contains( 'percentage' ) ) {
calculate();
}
if ( event.target.classList.contains( 'time' ) ) {
calculate();
}
output.innerHTML = `${finalOutput ? finalOutput : ""}`
}, false);
I just want to get the square root of total2 .. but it won't appear in the selected box ..
here is the javascript codes.
i'll comment the html codes.
function myFunction() {
var q1 = document.getElementById("qinput1").value;
var q2 = document.getElementById("qinput2").value;
var q3 = document.getElementById("qinput3").value;
var total = parseInt(q1) + parseInt(q2) + parseInt(q3);
document.getElementById("ainput3").value=total;
var a1 = document.getElementById("ainput1").value;
var a2 = document.getElementById("ainput2").value;
//from the total we got, lets assign it a variable for further calculation
var a3 = document.getElementById("ainput3").value=total;
var total2 = parseInt(a1)*parseInt(a2)/ parseInt(a3);
document.getElementById("ansA").value = total2;
var total3 = math.sqrt(parseInt(total2));
document.getElementById("sqaureD").value = total3;
}
function myShapes() {
document.getElementById('squareA').style.display =
document.getElementById('shapes').value == 'Square' ? 'block' : 'none'
}
<form action="" id="fcalculation">
<fieldset>
<legend>Calculation of qu</legend>
<label><i>Ultimate bearing capacity</i> <b>(qu) = </b></label>
<input id="qinput1" type="text" placeholder="c'NcFcsFcdFci"/> +
<input id="qinput2" type="text" placeholder="qNqFqsFqdFqi"/> +
<input id="qinput3" type="text" placeholder="½βγNFγsFγdFγi"/>
</fieldset>
</form>
it seems that the calculation part at the very end is not working. sorry its my first time to code.
Classname is Math not math
Try replacing
var total3 = math.sqrt(parseInt(total2,10));
with
var total3 = Math.sqrt(parseInt(total2,10));
Also, looking at your markup, there are no fields with id ainput1, ainput2 and ainput3.
I'm attempting to create a webpage that will allow my employees to enter a number and get a number that has run through an equation. I want it to do two simple math problems as follows and output the number that's larger.
Equations
x+150=y
x*1.5+89=z
Then display the larger variable.
I can't get it to work.
I'm pretty sure it's a major noob mistake.
<script type="text/javascript">
function updateOutput() {
//get form
var form = document.getElementById("calc");
//get output
var out = form.elements["z"];
//get two numbers
var num1 = parseInt(form.elements["x"].value);
//add 150
var num2 = 150;
//multiply 1.5;
var num3 = 1.5;
//add 89
var num4 = 89;
//amount1
var amount1;
//amount2
var amount2;
//set output depending on amount
//add
amount1.value = num1+num2;
//multiple
amount2.value = num1*num3+num4;
If amount1 > amount2 Then
out.value = amount1.value
Else
out.value = amount2.value
}
</script>
Some errors:
amount1.value only works if you define amount as Object, and it doesn't need to be object here. Same for amount2.
if else notation error
Better go to some tutorial sites like w3school or codecademy or buy some books.
Changes of your code, with added form, input to demonstrate.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="calc">
<input type="number" name="x"/>
<input type="number" name="z"/>
</form>
<button onclick="updateOutput();">click</button>
<script>
function updateOutput() {
//get form
var form = document.getElementById("calc");
//get output
var out = form.elements["z"];
//get two numbers
var num1 = parseInt(form.elements["x"].value);
//add 150
var num2 = 150;
//multiply 1.5;
var num3 = 1.5;
//add 89
var num4 = 89;
//amount1
var amount1;
//amount2
var amount2;
//set output depending on amount
//add
// It's ok to just assign value to them.
amount1 = num1+num2;
//multiple
amount2 = num1*num3+num4;
// Also here, don't use amountX.value.
if (amount1 > amount2) {
out.value = amount1
} else {
out.value = amount2
}
}
</script>