Run javascript with value of field onload - javascript

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">

Related

Jquery / javascript error to get live result in my project

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">

How to calculate subtotal and total and show the result using jquery

I have a purshase form with two items.
the first item which is a number box who identify how many adults in the trip.
the second item which is a number box who identify how many seniors in the trip.
for example :
I want when I select 2 in the first number box, the subtotal next to the number box show me the result of the calculation ( price of one person * 2)
also for seniors section.
I found a code which is work with select and option value :
update_amounts();
$('select').change(update_amounts);
function update_amounts() {
var sum = 0.0;
$('#tickets > tbody > tr').each(function () {
var qty = $(this).find('option:selected').val();
var price = $(this).find('.price').text().replace(/[^\d.]/, '');
var amount = (qty * price);
sum += amount;
$(this).find('.subtotal').text('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + amount);
});
$('#total').val('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + sum);
};
I have edited this code to my needs like this :
$('input').change(update_amounts);
function update_amounts() {
var sum = 0.0;
$('#tickets > tbody > tr').each(function () {
var qty1 = $(this).find('#adults').val();
var qty2 = $(this).find('#senior').val();
var price = $(this).find('.price').text().replace(/[^\d.]/, '');
var amount = ((qty1+qty2) * price);
sum += amount;
$(this).find('.subtotal').text('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + amount);
});
$('#total').val('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + sum);
};
But it doesn't work!
this is the Html code :
<input type="number" name="adult_count" id="adults" min="0" required>
<input type="number" name="senior_count" id="seniors" min="0" required>
this image shows what I need :
https://i.ibb.co/52qzkh7/stack2.png

Why is my form outputting NaN?

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.

balancing two input number fields in jquery

I would like to balance two input number fields using jquery based on the max value set for both. for example its like a balance, if one side goes down the other goes up and vice versa. another example if the max value is 20 then if i enter 5 in input field one then 15 would be left in input field two.
Need the help Thanks. Haven't started coding it as yet stuck trying to figure it out.
First you need to attach the input eventhandler on all of the relevant input fields. This event handler will compare the current input value of a input fields to the total/max value variable and find the remainder accordingly. The event handler then finds the other input fields and assigns them with the appropriate remainder values.
Note: This allows you to add as many inputs as you want and it will
balance them all out. Just remember to add the balance class on the
input field.
var total = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
this.value = value = 0;
} else if (value > total) {
this.value = value = total;
}/* else if (value < 0) {
this.value = value = 0;
}
* Remove this comment if value shouldn't be negative.
*/
var remainder = total - value;
var otherInputs = $('.balance');
otherInputs.splice($.inArray(this,otherInputs),1);
var remainderDiv = remainder/otherInputs.length;
$.each(otherInputs, function(input) {
otherInputs[input].value = remainderDiv;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
Update: The two inputs can be less than the max but never higher.
var max = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
value = 0;
}
var otherInputs = $('.balance');
var sum = 0;
$.each(otherInputs, function(input) {
sum += parseInt(otherInputs[input].value);
});
if (sum > max)
this.value = max - (sum - value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
here's a fiddle to get you started (and maybe finished):
https://jsfiddle.net/ahmadabdul3/xwyrrw53/1/
html:
<input type='number' id='first' class='balancable'/>
<input type='number' id='second' class='balancable'/>
js:
$(function() {
var max = 20;
var balanceOpposite = {
'first': 'second',
'second': 'first',
}
$('.balancable').on('input', function() {
var id = $(this).attr('id');
var thisVal = $(this).val();
$('#' + balanceOpposite[id]).val(20 - thisVal);
});
});

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

Categories