JavaScript Calculating wrong - javascript

I am trying to perform calculation using JavaScript. When user enter less than 10 pages in input (#page) the cost is 1. if he adds more than 10, each page costs .10. there are 2 options for checkbox, if he clicks first checkbox 10 is added and second checkbox 15 is added.
This is working when it is done in sequential steps. (input then clicking checkbox).
Ex: Input is : 9 (total: 1)
click checkbox1 - duplicates (total : 11)
click checkbox1 - laser (total: 26)
Now if i change the Input to 11, then the total becomes 1.10 - even if both the checkboxes are checked.. (expected result should be - 26.10)
I am not sure how to do this...can anyone help me out
<html>
<head>
<title>Calculation</title>
<script>
function calculate() {
var pages=document.getElementById("page").value;
if(pages <=10) {
total.value=1;
}
if(pages >= 11) {
var extra_pages= pages - 10;
var new_total= extra_pages * .10;
var new_total1= 1 + new_total;
total.value= new_total1;
}
}
function checkbox1() {
if(document.getElementById("ckbox1").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 10;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox1").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 10;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
function checkbox2() {
if(document.getElementById("ckbox2").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 15;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox2").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 15;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
</script>
<body>
Enter a Number: <input type="text" id="page" value="1" oninput="calculate()">
<br>
<br><br><br><br>
duplicates <input type="checkbox" id="ckbox1" onclick="checkbox1()">
laser print: <input type="checkbox" id="ckbox2" onclick="checkbox2()"> <br><br>
Total: <input type="text" id="total">
</body>
</html>

You can use calculate for all changes instead of creating each one for each input, which makes the calculation complex.
// Get reference to inputs.
var page = document.getElementById("page");
var total = document.getElementById("total");
var dup = document.getElementById("ckbox1");
var laser = document.getElementById("ckbox2");
function calculate() {
// To Number
var pages = parseInt(page.value, 10);
var value = 0;
if (pages <= 10) {
value = 1;
} else {
var extra_pages = pages - 10;
var new_total = extra_pages * .10;
var new_total1 = 1 + new_total;
value = new_total1;
}
// Add 10 if dup is checked.
if (dup.checked) {
value += 10;
}
// Add 15 if laser is checked.
// These can be moved out like
// const laserVal = 15;
// value += laserVal if you don't want magic number here.
if (laser.checked) {
value += 15;
}
// Truncate float.
total.value = value.toFixed(1);
}
Enter a Number:
<input type="text" id="page" value="1" oninput="calculate()">
<br>
<br>
<br>
<br>
<br>
duplicates:<input type="checkbox" id="ckbox1" onclick="calculate()">
laser print:<input type="checkbox" id="ckbox2" onclick="calculate()">
<br>
<br>Total:
<input type="text" id="total">

Related

How to implement an if-statement in an order form

I'm building a simple order form with some calculations with number & hidden fields (for email and autoresponder).
When the user input field is not '0' i want it to calculate the delivery cost in the total price. In the script below the Delivery cost always returns '0' even when the user field is not '0'.
If I change the value to a certain value it always returns that value even when the user field is '0'. So the IF is wrong somehow.
/* Get the values from the user*/
function getAantal() {
var AantalBoek = document.getElementById('AantalBoek').value;
var AantalCD = document.getElementById('AantalCD').value;
var AantalSoundtrack = document.getElementById('AantalSoundtrack').value;
/* Product variables*/
var PrijsBoek = document.getElementById('PrijsBoek').value;
var PrijsCD = document.getElementById('PrijsCD').value;
var PrijsSoundtrack = document.getElementById('PrijsSoundtrack').value;
/* Delivery variables, Soundtrack does not have delivery*/
/* in my logic the IF says: if user fills in 0 for AantalBoek,
then VerzendingBoek is 0 instead of 7. But it always returns 0, even if AantalBoek is 1*/
var VerzendingBoek = document.getElementById('VerzendingBoek').value;
if (AantalBoek !== null && AantalBoek !== '') {
VerzendingBoek = 0;
}
var VerzendingCD = document.getElementById('VerzendingCD').value;
if (AantalCD !== null && AantalCD !== '') {
VerzendingCD = 0;
}
/* Calculation of the Product total*/
var SubTotaalBoek = PrijsBoek * AantalBoek;
var SubTotaalCD = PrijsCD * AantalCD;
var SubTotaalSoundtrack = PrijsSoundtrack * AantalSoundtrack;
/* Calculation of the Delivery total*/
var TotaalVerzending = +VerzendingBoek + +VerzendingCD;
/* Calculation of the Final total*/
var Totaal = +SubTotaalBoek + +SubTotaalCD + +SubTotaalSoundtrack + +TotaalVerzending;
document.getElementById('Verzending').value = TotaalVerzending;
document.getElementById('TotaalPrijs').value = Totaal;
}
<!-- user defines values here: -->
<input type="number" id="AantalBoek" required="" onchange="getAantal()">
<input type="number" id="AantalCD" required="" onchange="getAantal()">
<input type="number" id="AantalSoundtrack" required="" onchange="getAantal()">
<!-- set values for the products: -->
<input type="hidden" id="PrijsBoek" name="PrijsBoek" value="15">
<input type="hidden" id="PrijsCD" name="PrijsCD" value="4">
<input type="hidden" id="PrijsSoundtrack" name="PrijsSoundtrack" value="2">
<!-- set values for the delivery cost: -->
<input type="hidden" id="VerzendingBoek" name="VerzendingBoek" value="7">
<input type="hidden" id="VerzendingCD" name="VerzendingCD" value="2">
<!-- totals are shown here (only for autorespond) -->
<input type="hidden" id="Verzending" name="Verzending">
<input type="hidden" id="TotaalPrijs" name="TotaalPrijs">
Ok i've started over, looking again at the if-statement and i found a syntax error, changed the condition and added an else statement.
The corrected script is this:
function getAantal(){
var AantalBoek = document.getElementById('AantalBoek').value;
var AantalCD = document.getElementById('AantalCD').value;
var AantalSoundtrack = document.getElementById('AantalSoundtrack').value;
var PrijsBoek = document.getElementById('PrijsBoek').value;
var PrijsCD = document.getElementById('PrijsCD').value;
var PrijsSoundtrack = document.getElementById('PrijsSoundtrack').value;
var VerzendingBoek = document.getElementById('VerzendingBoek').value;
/* Here I changed the condition: IF the user value is 0 then the delivery cost is 0,
ELSE use the value that was already defined:*/
if(AantalBoek == 0) { VerzendingBoek = 0;
} else {VerzendingBoek = document.getElementById('VerzendingBoek').value;
}
var VerzendingCD = document.getElementById('VerzendingCD').value;
if(AantalCD == 0) { VerzendingCD = 0;
} else {VerzendingCD = document.getElementById('VerzendingCD').value;
}
/*for the second condition i corrected the syntax error !== to !=,
IF delivery cost for Boek is not 0, then delivery cost for CD is 0*/
if (VerzendingBoek != 0) { VerzendingCD = 0;
}
var SubTotaalBoek = PrijsBoek * AantalBoek;
var SubTotaalCD = PrijsCD * AantalCD;
var SubTotaalSoundtrack = PrijsSoundtrack * AantalSoundtrack;
var TotaalVerzending = +VerzendingBoek + +VerzendingCD;
var Totaal = +SubTotaalBoek + +SubTotaalCD + +SubTotaalSoundtrack + +TotaalVerzending;
document.getElementById('Verzending').value=TotaalVerzending;
document.getElementById('TotaalPrijs').value=Totaal;
}

Create three input box and named it as Min,Max and Mul respectively with one Button named it as "Validate". using Javascript

Requirement 1: Create three input boxes and named it as Min,Max and Mul respectively.
Requirement 2: Create a button and named it as "Validate".
Requirement 3: Following conditions on the input box should get satisfied.
1) Min<Max
2) Mul<Max
3) Mul<=Min
4) Min and Mul should be the factor of Max.
For eg : We have three inputs
Min Max Mul
5 10 5
Requirement 4: If any conditions get false, then that box should be highlighted by making the border of that box as "red".
For eg : We have three inputs:
Min Max Mul
5 10 6
Try this:
const min = document.getElementById('min')
const max = document.getElementById('max')
const mul = document.getElementById('mul')
const validate = () => {
const minValue = Number(min.value)
const maxValue = Number(max.value)
const mulValue = Number(mul.value)
if (minValue < maxValue &&
maxValue % minValue === 0) min.classList.remove('invalid')
else min.classList.add('invalid')
if (mulValue < maxValue &&
mulValue <= minValue &&
maxValue % minValue === 0) mul.classList.remove('invalid')
else mul.classList.add('invaid')
}
input.invalid {
border: 2px solid red;
}
<label for="min">Min</label>
<input type="number" id="min" name="min">
<br>
<label for="max">Max</label>
<input type="number" id="max" name="max">
<br>
<label for="mul">Mul</label>
<input type="number" id="mul" name="mul">
<br>
<button onclick="validate()">Validate</button>
Note: This will not work in IE.
function myFunction() {
var min=document.getElementById("demo1").value;
var max=document.getElementById("demo2").value;
var mul=document.getElementById("demo3").value;
min = parseInt(min);
max = parseInt(max);
mul = parseInt(mul);
if(!(min < max)){
document.getElementById('demo1').style.borderColor = "red";
}else{
document.getElementById('demo1').style.borderColor = "";
}
if(!(max > mul)){
document.getElementById('demo2').style.borderColor = "red";
} else{
document.getElementById('demo2').style.borderColor = "";
}
if(!(mul<= min)){
document.getElementById('demo3').style.borderColor = "red";
} else{
document.getElementById('demo3').style.borderColor = "";
}
if(!(max%min==0)){
document.getElementById('demo1').style.borderColor = "red";
} else{
document.getElementById('demo1').style.borderColor = "";
}
if(!(max%mul==0)){
document.getElementById('demo3').style.borderColor = "red";
} else{
document.getElementById('demo3').style.borderColor = "";
}
}
<html>
<body>
Min:<input type="text" name="a" id="demo1"><br>
Max:<input type="text" name="b" id="demo2"><br>
Mul:<input type="text" name="c" id="demo3"><br>
<button onclick="myFunction()"> Validate</button><br>
</body>
</html>

I stuck with this code, trying to figure out, how it should work

I'm working on a poject, need it must be auto calculation.
let say that we have uncounted hidden inputs with known same class and attr. diffrent value, attr diffrent price, price2 price 3 in a div to count
What im trying to do is to get attrs (price, priceX2, priceX3)
if the user inserted a number ex. 1 or 40, will return first input(price, priceX2, priceX3), and if its given 61 0r 70 then it will return to the third input(price, priceX2, priceX3) so on
<div id="countDiv">
<input type="number" value="" id="counter" />
<button id="countBtn"> Count </button>
<input type="hidden" value="40" price="1100" priceX2="1200" priceX3="1220" class="classeid">
<input type="hidden" value="60" price="1150" priceX2="1250" priceX3="1300" class="classeid">
<input type="hidden" value="70" price="1220" priceX2="1350" priceX3="1400" class="classeid">
</div>
<script>
$(document).ready(function(){
$("#countBtn").click(function(){
var parentDOM = document.getElementById("countDiv");
var classCounter = parentDOM.getElementsByClassName("classeid");
var counter = $("#counter").val();
for (var i = 0, n = classCounter.length; i < n; ++i) {
var mPrice = parseInt(classCounter[i].value);
var cPrice = parseInt(classCounter[i].getAttribute('price'));
var cPriceX2 = parseInt(classCounter[i].getAttribute('priceX2'));
var cPriceX3 = parseInt(classCounter[i].getAttribute('priceX3'));
}
});
});
</script>
Hope this code help you.
Do do it dynamically it's not better to do using the Hidden field if you have more than 3 input hidden field. The logic will be different in that case.
Considering only 3 hidden input fields then code looks as below:
HTML Code:
provide id to the each hidden input fields as first, second and third as written in the code.
JavaScript Code:
$("#countBtn").click(function(){
var counter = $("#counter").val();
if(counter > 0 && counter <= 40) {
var mprice = $("#first").val();
var cprice = $("#first").attr("price");
var cPriceX2 = $("#first").val("priceX2");
var cPriceX3 = $("#first").attr("priceX3");
}
else if(counter > 39 && counter <= 60) {
var mprice = $("#second").val();
var cprice = $("#second").attr("price");
var cPriceX2 = $("#second").val("priceX2");
var cPriceX3 = $("#second").attr("priceX3");
}
else {
var mprice = $("#third").val();
var cprice = $("#third").attr("price");
var cPriceX2 = $("#third").val("priceX2");
var cPriceX3 = $("#third").attr("priceX3");
}
}

How to calculate total?

I faced a problem for my code and I could not solve it. I have 2 functions, the first one calculates the total and second one discounts the total (if the user write the discount code, it will show the discounted total). But I don't know how to get and call the right value from total to keep it in the second function to calculate the discount because it always shows 0 in the amount. The TOTAL is for the first function and JavaScript code is for the second function.
total = parseInt(TicketsPrice[i].value) * parseInt(NOfTictet);
document.getElementById("total").innerHTML = total;
function discount(coupon) {
var yCoupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var amount;
var input = document.getElementById('discount').value;
if (input == coupon) {
amount = price || 0 * 0.25;
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>
Something like this?
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').value);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * (1 - .25) // 25% off coupon
document.getElementById("Offerprice").innerHTML = amount;
} else {
document.getElementById("Offerprice").innerHTML = 'Invalid coupon'
}
}
<div>Total: <input id="total"></div>
<div>Coupon: <input id="discount"></div>
<button onclick="discount()"> discount</button>
<p><span id ="Offerprice"></span></p>
You have several issues in your code. Here is a working version. I hardcoded the total only for testing because I don't know the HTML for your tickets:
var total = 500; //This is only for testing.
document.getElementById("total").innerHTML = total;
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * 0.75; //discount of 25%
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>

jquery bunch of input values multiply by dynamic (another input)

I have a grouped product and that all group can buy within a page. Page has multiple quantity inputs (like 6). And another bulk quantity input.
What it must do is,
After setting the normal product quantities, those values must multiply by the bulk input value.
my code does the multiplication, but not as i expect. It just multiply by the current input value. I want to do as follows.
(1st attempt)
Eg : Input 1 Value = 5, Input 2 value = 2, Input 3 Value = 8. Bulk Value = 10
Results should be : Input 1 = 50, Input 2 = 20, Input 3 = 80
If we gain the bulk value by 1 (2nd attempt)
current Input 1 Value = 50, current Input 2 value = 20, current Input 3 Value = 80. new gained Bulk Value = 11
Results should be : Input 1 = 55, Input 2 = 22, Input 3 = 88
$('#multiply-value').change(function() {
var multiplied = $('#multiply-value').val();
var milti = 0;
var value_of = 0;
var test = 0;
if (this.getAttribute('value') === this.value) {
$(this).data('lastvalue', this.value);
} else {
if(this.value < $(this).data('lastvalue')){
var old = $(this).data('lastvalue');
console.log('decrement');
$('.input-text.qty').each(function() {
var i = 1;
var qty_vals = $(this);
var old_v = $(this).data('lastvalue');
old_test = old_v.val();
test = qty_vals.val();
var cals = 0;
while(i < multiplied ){
cals = +old_test + +cals;
console.log(cals);
i++
}
$(this).val(cals);
test = 0;
});
}
else{
console.log('increment');
$('.input-text.qty').each(function() {
var i = 1;
var qty_vals = $(this);
test = qty_vals.val();
var cals = 0;
while(i <= multiplied ){
cals = +test + +cals;
console.log(cals);
i++
}
$(this).val(cals);
test = 0;
});
}
// console.log(this.value < $(this).data('lastvalue') ? 'decrement' : 'increment');
$(this).data('lastvalue', this.value);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class=""bunch-of-inputs">
<input type="text" name="super_group[50]" maxlength="12" value="0" title="Qty" class="input-text qty">
<input type="text" name="super_group[50]" maxlength="12" value="0" title="Qty" class="input-text qty">
<input type="text" name="super_group[50]" maxlength="12" value="0" title="Qty" class="input-text qty">
</div>
<input id="multiply-value" type="number" value="1">
</div>
why not to store the original value of each field at another field rather than the value field ?
so the html will be :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class=""bunch-of-inputs">
<input type="text" name="super_group[50]" maxlength="12" value="5" title="Qty" class="input-text qty" data-default="5">
<input type="text" name="super_group[50]" maxlength="12" value="2" title="Qty" class="input-text qty" data-default="2">
<input type="text" name="super_group[50]" maxlength="12" value="8" title="Qty" class="input-text qty" data-default="8">
</div>
<input id="multiply-value" type="number" value="1" >
</div>
And the js will be:
$('#multiply-value').on('input',function() {
var multiplied = $('#multiply-value').val();
$('.input-text.qty').each(function() {
$(this).val($(this).data('default') * multiplied);
});
})
this way we don't need to store the previous value, we have the default value any time
/* modification start */
firsttime = true;
zero = true;
$('#multiply-value').change(function() {
if (firsttime && zero) {
$('.input-text.qty').each(function() {
this.setAttribute('value', $(this).val());
firsttime = false;
if($(this).val() != 0) {
zero = false;
}
});
}
/* modification end */
var multiplied = $('#multiply-value').val();
var milti = 0;
var value_of = 0;
var test = 0;
if (this.getAttribute('value') === this.value) {
$(this).data('lastvalue', this.value);
} else {
if (this.value < $(this).data('lastvalue')) {
var old = $(this).data('lastvalue');
console.log('decrement');
$('.input-text.qty').each(function() {
var i = 1;
var qty_vals = $(this);
var old_v = $(this).data('lastvalue');
old_test = old_v.val();
test = qty_vals.val();
var cals = 0;
while (i < multiplied) {
cals = +old_test + +cals;
console.log(cals);
i++
}
$(this).val(cals);
test = 0;
});
}
else {
console.log('increment');
$('.input-text.qty').each(function() {
var i = 1;
var qty_vals = this; // modified, write this instead of $(this)
test = qty_vals.getAttribute('value'); // modification here
var cals = 0;
while (i <= multiplied) {
cals = +test + +cals;
console.log(cals);
i++
}
$(this).val(cals);
test = 0;
});
}
// console.log(this.value < $(this).data('lastvalue') ? 'decrement' : 'increment');
$(this).data('lastvalue', this.value);
}
})
The first inputs are set to respective value attributes. If all of the inputs are zero, then the second inputs will act as first inputs and so on. Instead of test = qty_vals.value; write, test = qty_vals.getAttribute('value'); to get original non-zero values.

Categories

Resources