Home > other >  jQuery price calculator - change price based on value from slider
jQuery price calculator - change price based on value from slider

Time:09-22

I'm struggling a little bit with a jQuery pricing calculator that i'm building. The principle is that there is a calculator that allows the user to use a slider to select a number of users between 10 and 249, which would then show a price. The basic version of this can be seen here:

https://jsfiddle.net/junglist781/Lm57kwtg/

const priceInput = document.querySelector('[name=price]');
const quantityInput = document.querySelector('[name=quantity]');
const total = document.querySelector('.total');
const quantityLabel = document.querySelector('.quantity-label');


// create functions we'll need
function calculateCost() {
  var price = '10';
  const quantity = quantityInput.value;
  
  const cost = price * quantity;
  console.log(cost);
  total.innerText = "£"   cost.toFixed(2);
}

function updateQuantityLabel() {
  const quantity = quantityInput.value;
  quantityLabel.innerText = quantity;

}

// on first run
calculateCost();

// add event listeners
priceInput.addEventListener('input', calculateCost);
quantityInput.addEventListener('input', calculateCost);
quantityInput.addEventListener('input', updateQuantityLabel);

However, I need to be able to adjust the base price based on the number of users. For example 10-49 is £10, 50-99 is £9 and 100 is £8, etc. How would I do that?

Thanks for any help in advance!

CodePudding user response:

you could have a separate function to calculate the base price and add that to the calculated price


// create functions we'll need
function calculateCost() {
  var price = '10';
  const quantity = quantityInput.value;
  const basePrice = calculateBasePrice(quantity);
  const cost = basePrice   (price * quantity);
  console.log(cost);
  total.innerText = "£"   cost.toFixed(2);
}

function calculateBasePrice(qty) {
     var basePrice = 0;
     if (qty >= 10 && qty < 50) {
         basePrice = 10
     } else if (qty >= 50 && qty < 100) {
         basePrice = 9
     }
     return basePrice;
}
  • Related