mardi 26 janvier 2021

How to link a slider and checkbox to a counter?

I am new in JavaScript. I am trying to link a slider and checkbox to a counter. The slider should increase the counter's value depending on the range. And then the checkboxes have fixes values that they should add to the counter if it is checked or not.

var slider = document.querySelector('#myRange');                               //Input
var output = document.querySelector("#value-range");                           //Output
let rangeValue = document.querySelector('#final-price');                       //Counter
const boxesContainer = document.querySelector('.price-boxes__container');      //Checkboxes

I created an event for the checkboxes, so when you click on it, adds the value.

boxesContainer.onchange = function(e) {
    if (e.target.classList.contains('checkbox')){
        const price = parseInt(e.target.getAttribute('value'))
        if (e.target.checked === true) {
            total += price;
        } else {
            total -= price;
        }
        rangeValue.innerHTML = total
    }
}

And I created another event for the slider as well.

slider.oninput = function () {
    let value = slider.value;
    userPrice(value)    
    output.style.left = (value/2.88);
    output.classList.add("show");
    rangeValue.innerHTML = prices[value-25];
       
    function userPrice (value) {
        if (value == 25) {
            output.innerHTML = '6 €p'
        } else {
            output.textContent = `${prices[value-25] - prices[value-26]} €p`;
        }
    }
}

The slider has min 25, max 1000, step = 1, value = 25. Each step is one user. I created an array that has the price depending on the slider's value. Between 26-50 users 6€ per user, 51-250 4€/p, 251-500 3€/p and 501-1000 2€/p. Therefore, I thought the easy way was to create an array and use the slider's value to sent the price to the counter.

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
let rangePrices = range(25, 1000, 1);

const prices = [];

rangePrices.forEach((rangeValue, i)=> {
    if(rangeValue === 25) {
        prices.push(299)
    } else if (rangeValue < 51) {
         prices.push(prices[i-1] + 6)
    } else if (rangeValue < 251){
        prices.push(prices[i-1] + 4)
    } else if (rangeValue < 501) {
        prices.push(prices[i-1] + 3)
    } else {
        prices.push(prices[i-1] + 2)
    }
});

But at the end, when I click on the checkboxes the counter adds the checkboxes' values, but it resets. I know that I have two rangeValue.innerHTML and is due to this that it does not work, but I do not know how to fix it...

It would be great if someone could help me!



Aucun commentaire:

Enregistrer un commentaire