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
Related
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>
I have a product page where you can make customizations to the product such as adding or removing "ingredients" and for each customization that can be added or removed I create an input with a + and - button to increase or decrease my choice.
I inform via parameter to the javascript function the component (input) that will receive the increment or decrement, the maximum value that can be increased, the minimum value (decrement) and the increment interval.
However, for each possible customization in the product I must present a component like this:
<div class="qty mt-5">
<span class="minus" name="diminuir[]" onclick="AumentaDiminui('qty_4', 0, 5, 1)">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]" onclick="AumentaDiminui('qty_4', 0, 5, 1)">+</span>
</div>
And this is my java script function that should add or subtract the value and present it in the correct input
<script>
function AumentaDiminui(controle, valorMinimo, valorMaximo, valorIncremento) {
$(document).ready(function () {
$('[name="aumentar[]"]').click(function () {
if ($("[name=" + controle + "]").val() == valorMaximo)
return;
$("[name=" + controle + "]").val(parseInt($("[name=" + controle + "]").val()) + valorIncremento);
});
$('[name="diminuir[]"]').click(function () {
if ($("[name=" + controle + "]").val() <= valorMinimo) {
$("[name=" + controle + "]").val(valorMinimo);
return;
}
$("[name=" + controle + "]").val(parseInt($("[name=" + controle + "]").val()) - valorIncremento);
});
});
}
</script>
It turns out that the value is not incremented by 1 in 1 as I inform via parameter and if I have more than one component on the screen, when clicking on + or - the value of all inputs are changed regardless of the button I click on
A few comments about your code:
If jquery will handle the click events on the <span>, one should not define a onclick event in the span tag.
There is no need to define a function. You can just wait for the ready event and then monitor for clicks on both <span> (using the jquery .click() function).
You can access the values of min and max value defined in the <input> using the jquery .attr() function.
This is a working code:
$(document).ready(function () {
$('.qty .minus, .qty .plus').click(function () {
var input = $(this).parent().find('input[type=number]');
var newVal = +input.val();
var step = +input.attr('step');
if ($(this).hasClass('plus')){
newVal += step;
} else {
newVal -= step;
}
var min = input.attr('min');
var max = input.attr('max');
if (newVal > max) {
newVal = max;
} else if (newVal < min){
newVal = min;
}
input.val(newVal);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Step: 1</p>
<div class="qty mt-5">
<span class="minus">-</span>
<input type="number" class="count" value="0" step="1" max="5" min="0">
<span class="plus">+</span>
</div>
<p>Step: 2</p>
<div class="qty mt-5">
<span class="minus">-</span>
<input type="number" class="count" value="0" step="2" max="5" min="0">
<span class="plus">+</span>
</div>
There is a much easier way to do this, with just a few data-* attributes. This will work on any number of div elements with these attributes and a plus and minus button.
$('.qty').on('click','.minus', function(){
var $parent = $(this).parent();
var min = $parent.data('min');
var inc = $parent.data('inc');
var $input = $(this).siblings('.count');
var val = parseInt($input.val(),10);
if(val > min)
$input.val(val - inc);
})
$('.qty').on('click','.plus', function(){
var $parent = $(this).parent();
var max = $parent.data('max');
var inc = $parent.data('inc');
var $input = $(this).siblings('.count');
var val = parseInt($input.val(),10);
if(val < max)
$input.val(val + inc);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="qty mt-5" data-min="0" data-max="5" data-inc="1">
<span class="minus">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]">+</span>
</div>
<div class="qty mt-5" data-min="0" data-max="100" data-inc="5">
<span class="minus">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]">+</span>
</div>
You could also choose to read min, max and step from the input if you prefered with much the same logic.
create an jquery extension
(function($){
$.fn.AumentaDiminui = function(options) {
var settings = $.extend({ control: null, minvalue:1, maxvalue: 5 , action:'+' }, options );
var curval = $(settings .control).val ();
if ('+'==settings.action){
if (curval==settings.maxvalue) return;
curval++;
}
else {
if (curval==settings.minvalue) return;
curval++;
}
$(settings .control).val (curval);
};
}(jQuery));
call so as
$('div.qty.mt-5 span.minus').click(function (){ $.fn.AumentaDiminui({ action:'-', control:'div.qty.mt-5 input.count' }); });
$('div.qty.mt-5 span.plus').click(function (){ $.fn.AumentaDiminui({ action:'+', control:'div.qty.mt-5 input.count' }); });
I'm trying to make a loan calculator by making two range slider interact with one another then show a the monthly payments in a label, these are the two requirements:
Only show 5 values on the "Month" range slider: 12,18,24,30,36 months (solved by Alexander Solonik)
Calculate an interest of 75%. (solved myself)
ok the code has evolved this way,:
<!--first range slider: money needed to borrow-->
<script language="JavaScript">
function showpay() {
var princ = document.calc.loan.value;
var term = document.calc.months.value;
var intr = (75 / 1200)*1.16; /*must include taxes, depending on your country, in my case is 16%*/
var auxterm = 0;
switch(term){
case '1': auxterm = 12; break;
case '2': auxterm = 18; break;
case '3': auxterm = 24; break;
case '4': auxterm = 30; break;
case '5': auxterm = 36; break;
}
document.calc.pay.value = Math.round((princ * 1000) * intr / (1 - (Math.pow(1/(1 + intr), auxterm))));
// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))
}
</script>
<center>
<form name=calc method=POST>
<table width=60% border=0>
<h1>¿How much money do you need?</h1>
<p>Borrow from $2,000 to $80,000</p><br>
<div>
<input name="loan" type="range" min="2" max="80" value="2" class="slider" id="myRange" style="color: black;">
<p><br><strong>$ <span id="demo"></span>,000</strong></p>
</div>
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() { output.innerHTML = this.value; }
</script>
<h1>In how many months would you like to pay?</h1>
<p>from 12 to 36 months.</p><br>
<div>
<input name="months" type="range" min="1" max="5" value="0" class="slider" id="input" style="color: black;">
<strong><p><span id="result"></span> months</p></strong>
</div>
<script>
var result = document.getElementById('result'), input = document.getElementById('input')
var arr = [12,18,24,30,36]
input.oninput = function() { result.innerHTML = arr[this.value - 1] }
input.oninput()
</script>
<!--<tr>
<p>$ <span oninput="showpay()" value=Calculate></span></p>
</tr>-->
<tr>
Monthly Payment
<input type=text name=pay size=10>
</tr>
<input type=button onClick='showpay()' value=Calculate><!-- oninput="showpay()"-->
</table>
</form>
</center>
It is basicly complete, however the interest calculation is wrong, on the month slider it takes the values: 1,2,3,4,5 as that is the value of the slider, i need it to take the value of the arr = [12,18,24,30,36] instead, any idea how to do this?
ok this is now solved, may this be of help to some school projet or an actual loan calculator. :)
For only specific values o be selected in the range slider you can do something like this
var result = document.getElementById('result'),
input = document.getElementById('input')
var arr = [12,18,24,30,36]
input.oninput = function() {
result.innerHTML = arr[this.value - 1]
}
input.oninput()
<input type="range" min="1" max="5" id="input" value="0">
<div id="result">
</div>
You have a typo, its slider not lider.
Change on line 22 to
slider.oninput = function() { output.innerHTML = this.value; }
And the value is not visible because you applied CSS color value white in p tag. Also change that to
<p class="subtitulo" style="color: black;"><br><strong><span id="demo2"></span> months</strong></p>
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
Today I try to calculating the price from <span> value and <input> value. And then, put the result in <span>.
I already tried this code. This is my html:
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="quantity" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
So I want to get price value from <span id="price>, get quantity from <input type="text" id="quantity" name="quantity">, and put the result in <span id="total" class="amount"></span>
This is my script code:
<script type="text/javascript">
var price = parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price*qty;
$('#total').text(total);
</script>
Note: I am using JQuery for increase / decrease quantity (plus & minus button)
Did I wrote something wrong?
Thanks
UPDATE
This is my increase / decrease javascript code:
<script type="text/javascript">
jQuery(document).ready(function(){
// This button will increment the value
$('.plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".minus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>
The 'price' field is a span, which do not have a value property. Instead, you need to read the text() from it. Also note that the 'quantity' field has an id, so you would be better to use that as a selector as it's much faster. Try this:
var price = parseFloat($('#price').text()) || 0;
var qty = parseInt($('#quantity').val());
var total = price * qty;
$('#total').text(total);
Working example
var price = parseFloat($('#price').text()) || 0; //parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price * qty;
$('#total').text(total);
The .val() method is primarily used to get the values of form elements such as input , select and textarea
FIDDLE DEMO
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
.active {
color:red;
}
</style>
<script>
$(document).ready(function () {
var price = parseFloat($('#price').text()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price * qty;
$('#total').text(total);
});
</script>
</head>
<body>
<table>
<tr>
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="Text1" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
</tr>
</table>
</body>
</html>