js calculating total price from input number and show - javascript

I have three types for tickets. Children - cost 8$, retirees - cost 10$ and adults - cost 12$ and i have 3 input numbers and i want when someone of these three input change to calculate and print in html total price
This is my html
children<input type="number" id="children" name="children" min="0" max="20" value="0" onchange="myScript">
adults<input type="number" id="adults" name="adults" min="0" max="20" value="0" onchange="myScript">
retirees<input type="number" id="retirees" name="retirees" min="0" max="20" value="0" >
This is my js
function totalPrice(){
var total = 0
var children = document.getElementsByName('children');
var children = document.getElementsByName('adults');
var children = document.getElementsByName('retirees');
total = (parseInt(children) * 8) + (parseInt(adults) * 12) + (parseInt(retirees) * 10);
Here i dont know how to print in html total price
I want to look something like that

One possible way is to place a div for displaying Total in html
<div id="total"></div>
then attach an "eventListener" for change to each input field to trigger the calculation
document.querySelectorAll("input").forEach(el => {
el.addEventListener("change", () => {
totalPrice();
});
});
then update the value in html with:
totalDiv.innerHTML = `<h3>Total: ${total}$</h3>`;
Working Stackblitz

Given a div below the <inputs>, in the form of <div id="price"></div>
You could set the price this way:
let price_div = document.querySelector("#price")
// Apply whatever formatting to the price you want.
price_div.innerHTML = total

As these are input fields you can just use their value
function totalPrice(){
var total = 0
var children = document.getElementsByName('children');
var adults = document.getElementsByName('adults');
var retirees = document.getElementsByName('retirees');
total = (parseInt(children.value) * 8) + (parseInt(adults.value) * 12) + (parseInt(retirees.value) * 10);

function totalPrice(){
var total = 0
var children = document.getElementsByName('children')[0].value;
var adults = document.getElementsByName('adults')[0].value;
var retirees = document.getElementsByName('retirees')[0].value;
total = (children * 8) + (adults * 12) + (retirees * 10);
console.log(total);
document.getElementById('totalPrice').textContent=total;
}
children <input type="number" id="children" name="children" min="0" max="20" value="0" onKeyUp="totalPrice()">
adults <input type="number" id="adults" name="adults" min="0" max="20" value="0" onKeyUp="totalPrice()">
retirees <input type="number" id="retirees" name="retirees" min="0" max="20" value="0" onKeyUp="totalPrice()">
<div id="totalPrice" style="color:red"></div>

Related

How to reset JavaScript code when input value is changed?

I would like for the code to change its answer when I change the value of the input.
So let's say instead of 10, I would like it to tell me how much HP (health points) I will have at level 15. Is there any way I can do this? I'm not that experienced in Javascript.
So right now I coded it to default to 10 on all stats. My website tells me that at level 10, I have 895.4 hp. The only problem is that it won't stay at 15 when I try to press enter. It will just revert back to 10. Pretty much useless. Is there any way to keep that number 15 when I press enter?
var finalhp = 500;
let hpmultiplier = 1.06;
var hpvaluestring = document.querySelector('.hp').value;
var hpvalue = parseInt(hpvaluestring);
for (let i = 0; i < hpvalue; i++) {
var finalhp = finalhp * hpmultiplier
}
console.log(finalhp)
<form>
<div>
<input class="hp" id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
<input class="slider" id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div>
</form>
Add a form submit event listener to the form element and prevent form submission there.
<form onsubmit="submitForm(event)">
<div>
<input class="hp" id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
<input class="slider" id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div>
</form>
Add a submitForm function inside a script tag
function submitForm(event){
event.preventDefault();
var finalhp = 500;
let hpmultiplier = 1.06;
var hpvaluestring = document.querySelector('.hp').value;
var hpvalue = parseInt(hpvaluestring);
for (let i = 0; i < hpvalue; i++) {
var finalhp = finalhp * hpmultiplier
}
console.log(finalhp)
}
So mainly I'm just adding eventListeners to trigger the function calculateHP on input/slider value change. The function calculateHP contains the same logic that you shared. I did this so that the eventListeners can callback the function.
Try the following:
const input = document.querySelector('.hp')
const slider = document.querySelector('.slider')
slider.addEventListener('change', calculateHP)
input.addEventListener('change', calculateHP)
function calculateHP(){
let multiplier = 1.06
let level = Number(input.value)
let HP = 500
for(let i = 0; i<level; i++){
HP = HP * multiplier
}
return console.log(HP)
}
<div>
<label>Level: </label>
<input class="hp" id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
<input class="slider" id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div>

How to subtract two div by their ID?

I have some range sliders and input fields. From that I'm getting some equations now I want to subtract those dynamic numbers by their ID. Below is the code but I'm getting NaN value. Below the steps, I've done.
Getting #totalavgtime from the multiplication of range slider and .averagetime
Getting #timetoproduce from the multiplication of range slider and .radio-roi next input value.
Now trying to subtract #totalavgtime - #timetoproduce but getting NaN value in #timesaving.
$(document).ready(function() {
$(".range").on("change", function() {
var mult = 0;
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").attr("value"))
mult += parseInt($(this).val()) * selector_next //multply..
console.log($(".averagetime:eq(" + i + ")").attr("value"), $(this).val())
})
$("#totalavgtime").val(mult)
})
});
$(document).ready(function() {
$('.range').on('change', function() {
let n = $(this).attr('id').match(/\d+/g)[0];
let total = 0;
let checkVal = $('.radio-roi:checked').next('input').val();
let multiplyFactor = parseFloat(checkVal);
console.log(multiplyFactor)
$('.range').each(function() {
total += (parseFloat($(this).val()) * multiplyFactor);
});
$('#timetoproduce').value(total);
})
});
$(document).ready(function() {
var txt1 = parseInt(document.getElementById("totalavgtime").value);
var txt2 = parseFloat(document.getElementById("timetoproduce").value);
var res = document.getElementById("timesaving");
Number(txt1);
Number(txt2);
//Substract that
res.value = txt1 - txt2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text"value="6" id="avgtime-id" class="averagetime"disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><br>
<input type="text"id="totalavgtime" value="" disabled><br>
<input type="text"id="timetoproduce" value="" disabled><br>
<input type="text"id="timesaving" value="" disabled><br>
You can merge both event handler in one as both are triggering same elements . So , inside this on each iteration get value of range slider and add total to same variable and set them in required input . Now , to subtract them check if the value is not null depending on this take value of input else take 0 to avoid NaN error.
Demo Code :
$(document).ready(function() {
$(".range").on("change", function() {
$(this).next().text($(this).val()) //for output(range)
var selector_next_avg = 0;
var timetoproduce = 0
var checkVal = parseFloat($('.radio-roi:checked').next('input').val()); //radio next input
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").val()) //avg..input
selector_next_avg += parseInt($(this).val()) * selector_next;
timetoproduce += (parseFloat($(this).val()) * checkVal);
})
//set both values
$("#totalavgtime").val(selector_next_avg)
$('#timetoproduce').val(timetoproduce);
total() //call to total..(sub)
})
});
function total() {
var txt1 = $("#totalavgtime").val() != "" ? parseFloat($("#totalavgtime").val()) : 0; //if null take 0
var txt2 = $("#timetoproduce").val() != "" ? parseFloat($("#timetoproduce").val()) : 0;
$("#timesaving").val(txt1 - txt2); //set value
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text" value="6" id="avgtime-id" class="averagetime" disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><output></output><br>
<input type="text" id="totalavgtime" value="" disabled><br>
<input type="text" id="timetoproduce" value="" disabled><br>
<input type="text" id="timesaving" value="" disabled><br>

How to sum slider value to another value?

I have a slider in my web page which start with 50 and i have to calculate it's price with other inputs
50 equals to 0€ when i increase the slider the value should be added to my total input like
(sliderValue - 50) * 0.35
When i increase there is no issue
But when i decrease the value is not removed...
How can i manage it? here is an example
var slider = document.getElementById("sliderHDD");
var output = document.getElementById("risultato");
var lastVal = 0
slider.oninput = function() {
var value = this.value
var prezzo = (value - 50) * 0.35;
var totale = document.getElementById("totale")
output.innerHTML = value;
if (lastVal < value) {
// increase
totale.value = parseInt(totale.value) + parseInt(prezzo)
} else {
// decrease
totale.value = parseInt(totale.value) - parseInt(prezzo)
}
lastVal = value
document.getElementById("tothdd").value = prezzo;
}
<tr>
<td><input style="width: 50%" step="10" type="range" min="50" max="500" value="50" class="slider" id="sliderHDD"></td>
<td><span id="risultato" align="left"></span></td>
<td></td>
<td><input type="text" id="tothdd" disabled="disabled" value="0.00" style="width:60px"></td>
<td>€</td>
</tr>
<br>
Total
<input type="text" id="totale" name="CostTotale" disabled="disabled" value="0" style="width:45px" class="text">
As you can see if i increase slider to X the value will be 42 and even in total will be 42, but then if i change it's value again the total will be not as it have to be

Calculate and display total as range slider moves

I'm trying to calculate and display the result of three ranger sliders. The equation I'm trying to display is:
KM driven per year * Avg KM/100L / Price of fuel
I've gotten the sliders to display each of their individual values but I'm not sure how to display the calculation.
View Codepen
<div>
<p>KM Driven per Year</p>
<p id="myAvgKM"></p>
<input type="range" min="0" max="300000" value="80000" step="1000" class="slider" id="kmdriven">
<p>On average, my truck gets around:</p>
<div class="response-container">
<p id="myAvgKPL"></p>
<p>L/100KM</p>
</div>
<input type="range" min="4" max="60" value="40" id="avgkm">
<p>Diesel prices are usually:</p>
<p id="price"></p>
<input type="range" min="0.000" max="3.000" value="1.308" step=".001" id="priceValue">
</div>
<div>
<p>In the first year alone, our services would save you:</p>
<p id="savings"></p>
</div>
function calculate () {
// Display KM Driven Slider
var kmPerYear = document.getElementById("kmdriven")
var kmOutput = document.getElementById("myAvgKM")
kmOutput.innerHTML = kmPerYear.value;
kmPerYear.oninput = function() {
kmOutput.innerHTML = this.value;
}
// Display Avg Mileage
var avgKM = document.getElementById("avgkm")
var avgKMOutput = document.getElementById("myAvgKPL")
avgKMOutput.innerHTML = avgKM.value;
avgKM.oninput = function() {
avgKMOutput.innerHTML = this.value;
}
//Display Avg Price
var avgPrice = document.getElementById("priceValue")
var priceOutput = document.getElementById("price")
priceOutput.innerHTML = avgPrice.value;
avgPrice.oninput = function () {
priceOutput.innerHTML = this.value;
}
// The Math!
document.getElementById("savings").innerHTML = "$ ";
}
You need map your function to onchange event as
<input onchange="calculate()" type="range" min="0" max="300000" value="80000" step="1000" class="slider" id="kmdriven">
Remove oninput, because your slider don't handle oninput change to onchange
Add formula for total saving
var total = (kmPerYear.value / 100) * (avgKM.value * 1.2) * avgPrice.value;
document.getElementById("savings").innerHTML = `$ ${total}`;
function calculate () {
// Display KM Driven Slider
var kmPerYear = document.getElementById("kmdriven");
var kmOutput = document.getElementById("myAvgKM")
kmOutput.innerHTML = kmPerYear.value;
// Display Avg Mileage
var avgKM = document.getElementById("avgkm")
var avgKMOutput = document.getElementById("myAvgKPL")
avgKMOutput.innerHTML = avgKM.value;
//Display Avg Price
var avgPrice = document.getElementById("priceValue")
var priceOutput = document.getElementById("price")
priceOutput.innerHTML = avgPrice.value;
// The Math!
var total = (kmPerYear.value / 100) * (avgKM.value * 1.2) * avgPrice.value;
document.getElementById("savings").innerHTML = `$ ${total}`;
}
.response-container {
display: flex;
}
<div>
<p>KM Driven per Year</p>
<p id="myAvgKM"></p>
<input onchange="calculate()" type="range" min="0" max="300000" value="80000" step="1000" class="slider" id="kmdriven">
<p>On average, my truck gets around:</p>
<div class="response-container">
<p id="myAvgKPL"></p>
<p>L/100KM</p>
</div>
<input onchange="calculate()" type="range" min="4" max="60" value="40" id="avgkm">
<p>Diesel prices are usually:</p>
<p id="price"></p>
<input onchange="calculate()" type="range" min="0.000" max="3.000" value="1.308" step=".001" id="priceValue">
</div>
<div>
<p>In the first year alone, our services would save you:</p>
<p id="savings"></p>
</div>
Add the window onload script at end of your javascript file
window.onload=calculate;
https://codepen.io/sanjayism/pen/vYNaoap

Set max value of three input numbers together

I have three input numbers:
<input min="0" name="cat1" step="1" type="number" max="50" value="0" />
<input min="0" name="cat2" step="1" type="number" max="50" value="0" />
<input min="0" name="cat3" step="1" type="number" max="50" value="0" />
Currently the max value is 50. I would like the max for all three together to be 50 aswell.
How can I solve this with javascript or jquery?
This method sums the other inputs, and if the sum + the current value is greater than max, it changes the current input's value to fit max.
For example, try entering 30, 5, 20 to the input boxes.
var max = 50;
var $inputs = $('input');
function sumInputs($inputs) {
var sum = 0;
$inputs.each(function() {
sum += parseInt($(this).val(), 0);
});
return sum;
}
$inputs.on('input', function(e) {
var $this = $(this);
var sum = sumInputs($inputs.not(function(i, el) {
return el === e.target;
}));
var value = parseInt($this.val(), 10) || 0;
if(sum + value > max) $this.val(max - sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input min="0" name="cat1" step="1" type="number" max="50" value="0" />
<input min="0" name="cat2" step="1" type="number" max="50" value="0" />
<input min="0" name="cat3" step="1" type="number" max="50" value="0" />
Hope you expected this way.
Try Using this code.
it will check the aggregate of three fields and check it whether it is greater than 50.
$(":input").bind('keyup mouseup', function () {
var cat1=$("#cat1").val();
var cat2=$("#cat2").val();
var cat3=$("#cat3").val();
var total=parseInt(cat1) + parseInt(cat2) + parseInt(cat3);
if(total>50) {
alert("it exceeds 50");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input min="0" id="cat1" name="cat1" step="1" type="number" max="50" value="0" />
<input min="0" id="cat2" name="cat2" step="1" type="number" max="50" value="0" />
<input min="0" id="cat3" name="cat3" step="1" type="number" max="50" value="0" />
This will ensure the sum doesn't exceed 50. In case the new value makes the total exceed the limit, the other two will be lowered equally to enforce the total=50 rule.
Note the
let share2 = Math.min(Math.floor(excessValue / 2), elmt2Value) which ensures
To ensure we won't remove more from one of the input than its value.
<input min="0" name="cat1" id="cat1" step="1" type="number" max="50" value="0" onchange="valueChanged('cat1')" />
<input min="0" name="cat2" id="cat2" step="1" type="number" max="50" value="0" onchange="valueChanged('cat2')" />
<input min="0" name="cat3" id="cat3" step="1" type="number" max="50" value="0" onchange="valueChanged('cat3')" />
<script>
function valueChanged(changedElmtId) {
// Retrieve all input, the one changed and the other 2
let elmt2Id = "cat2", elmt3Id = "cat3"
if ( changedElmtId === elmt2Id ) {
elmt2Id = "cat1"
}
else if ( changedElmtId === elmt3Id ) {
elmt3Id = "cat1"
}
let changedElmt = document.querySelector("#" + changedElmtId)
let elmt2 = document.querySelector("#" + elmt2Id)
let elmt3 = document.querySelector("#" + elmt3Id)
let elmt2Value = parseInt(elmt2.value)
let elmt3Value = parseInt(elmt3.value)
// Check if any action is needed
let totalValue = parseInt(changedElmt.value) + elmt2Value + elmt3Value
if ( isNaN(totalValue) || totalValue <= 50 )
return
// Measure excess then split in 2
let excessValue = totalValue - 50
let share2 = Math.min(Math.floor(excessValue / 2), elmt2Value)
let share3 = excessValue - share2
console.log("Current:", " " + elmt2Id + ": ", share2, " " + elmt3Id + ": ", share3)
console.log("Total:", totalValue, " Excess: ", excessValue, " " + elmt2Id + ": ", share2, " " + elmt3Id + ": ", share3)
elmt2.value = elmt2Value - share2
elmt3.value = elmt3Value - share3
}
</script>
I don't know how optimal my solution is but it works. Covered some edge cases too.
let inputs = document.querySelectorAll('input');
const max = inputs[0].getAttribute("max");
let value;
inputs.forEach((input, i) => {
input.addEventListener('change',(e) =>handleChange(e)); // adding change event
input.addEventListener('blur',(e) =>handleChange(e)); //adding a blur eventto prevent direct typing of input larger than max
})
const handleChange = (e) =>{
if(e.target.value > max - value){
e.target.value = max-value; //setting max value possible if input value is greater than max
return;
}else{
value = 0;
inputs.forEach( input => {
value+=parseInt(input.value); //calculating value to negate from max
});
inputs.forEach( input => {
if(max-value > 0){
input.setAttribute("max", max-value); //setting max value on every input
}
});
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input min="0" name="cat1" step="1" type="number" max="50" value="0" />
<input min="0" name="cat2" step="1" type="number" max="50" value="0" />
<input min="0" name="cat3" step="1" type="number" max="50" value="0" />
</body>
</html>
I hope that works for you easy small and fast for lesser number of input in form.
$(function(){
$('input[type=number]').attr('max', '50')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input min="0" name="cat1" step="1" type="number" value="0" />
<input min="0" name="cat2" step="1" type="number" value="0" />
<input min="0" name="cat3" step="1" type="number" value="0" />

Categories

Resources