skip to Main Content

I have a form with 7 checkboxes that have a data-calculate attribute. I want to manipulate the data-calculate value when there are a consecutive 3 to 5 checked. To get the 1st discount and 3 up to 5 or more checkboxes to get the 2nd discount from my form.

I have tried many times to achieve what I want but nothing is working. Also with the else statement is kind of confusing how to remove items and working with the discounts and all.

I am sending you my whole form to check maybe someone can help me finish it.

let _log = (item) => {
  return console.log(item)
}

const week1 = document.querySelector(".c_week_1");
const week2 = document.querySelector(".c_week_2");
const week3 = document.querySelector(".c_week_3");
const week4 = document.querySelector(".c_week_4");
const week5 = document.querySelector(".c_week_5");
const week6 = document.querySelector(".c_week_6");
const week7 = document.querySelector(".c_week_7");

// Getting data attribute value
let week1Calc = week1.dataset.calculate;
let week2Calc = week2.dataset.calculate;
let week3Calc = week3.dataset.calculate;
let week4Calc = week4.dataset.calculate;
let week5Calc = week5.dataset.calculate;
let week6Calc = week6.dataset.calculate;
let week7Calc = week7.dataset.calculate;

// let sum = checkboxesCalculateValuesArray.reduce((accumulator, currentValue) => {
//         return parseInt(accumulator) + parseInt(currentValue);
//     });

// Output price
let price = document.querySelector(".c_final_price_1_kid");

// Initalial num
let count = 0;

// Arrays
// Selecting all inputs
let allCheckboxes = [week1, week2, week3, week4, week5, week6, week7];
// Selecting all inputs data-calculate value
let allCheckboxesCalcValues = [week1Calc, week2Calc, week3Calc, week4Calc, week5Calc, week6Calc, week7Calc];
// Adding all inputs that are checked
let checkboxesCheckedArray = [];
// Getting checkboxesCheckedArray index numbers
let checkboxesCheckedArrayNumbers = [];
// Adding the checked checkbox data-calculate attribute in the array
let checkboxesCalculateValuesArray = [];


// Selecting all checkboxes and their index
allCheckboxes.forEach((box, index) => {

  box.addEventListener("change", (e) => {

    if (box.checked) {

      // Check how many checkboxes are checked
      count++;

      // console.log(count)

      // Adding checked checkboxes to the array
      checkboxesCheckedArray.push(box);

      // Adding checked index to the array
      checkboxesCheckedArrayNumbers.push(index);

      // Sorting numbers array 
      checkboxesCheckedArrayNumbers.sort();

      checkboxesCalculateValuesArray.push(e.target.dataset.calculate);

      price.textContent = checkboxesCalculateValuesArray.reduce((accumulator, currentValue) => {
        return parseInt(accumulator) + parseInt(currentValue);
      });


      for (let i = 1; i < checkboxesCheckedArrayNumbers.length - 1; i++) {

        // Here are the 2 if statements. I am looking for consecutive checkboxes. 3 up to 5 and 3 up to 7

        // Check if 3 or more are in cunsecutive order
        if (checkboxesCheckedArrayNumbers[i - 1] === checkboxesCheckedArrayNumbers[i] - 1 && checkboxesCheckedArrayNumbers[i + 1] ===
          checkboxesCheckedArrayNumbers[i] + 1) {

          // When there are 3 up to 5 consecutive weeks then loop here to change data-calculate values to 84.15

          price.textContent = checkboxesCalculateValuesArray.reduce((accumulator, currentValue) => {
            return parseInt(accumulator) + parseInt(currentValue);
          });

          _log(checkboxesCalculateValuesArray)


        }


        // Check if 5 or more are in cunsecutive order
        if (checkboxesCheckedArrayNumbers[i - 2] === checkboxesCheckedArrayNumbers[i] - 2 && checkboxesCheckedArrayNumbers[i + 2] ===
          checkboxesCheckedArrayNumbers[i] + 2) {



        }

        // end of Check if 5 or more are in cunsecutive order

      }
      // End for loop


    } else {

      count--;

      console.log(count);

      // Adding checked checkboxes to the array
      checkboxesCheckedArray.pop(box);

      // Adding checked index to the array
      checkboxesCheckedArrayNumbers.pop(index);

      // Sorting numbers array 
      checkboxesCheckedArrayNumbers.sort();

      checkboxesCalculateValuesArray.pop(e.target.dataset.calculate);

      for (let i = 1; i < checkboxesCheckedArrayNumbers.length - 1; i++) {
        // Check if 3 or more are in cunsecutive order
        if (checkboxesCheckedArrayNumbers[i - 1] === checkboxesCheckedArrayNumbers[i] - 1 && checkboxesCheckedArrayNumbers[i + 1] ===
          checkboxesCheckedArrayNumbers[i] + 1) {


        }
        // END OF Check if 5 or more are in cunsecutive order

        // Check if 5 or more are in cunsecutive order

        if (checkboxesCheckedArrayNumbers[i - 2] === checkboxesCheckedArrayNumbers[i] - 2 && checkboxesCheckedArrayNumbers[i + 2] ===
          checkboxesCheckedArrayNumbers[i] + 2) {



        }

      }

    }

  })

})

let customForm = document.getElementsByTagName("form")[0];
const submitButton = document.querySelector(".c-main-calc-submit--button");
// _log(submitButton)

customForm.addEventListener("submit", (e) => {
  customForm.submit();
})
<form id="form">
  <div class="c-checkbox-box">
    <span>1</span>
    <input type="checkbox" class="c_week_1" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>2</span>
    <input type="checkbox" class="c_week_2" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>3</span>
    <input type="checkbox" class="c_week_3" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>4</span>
    <input type="checkbox" class="c_week_4" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>5</span>
    <input type="checkbox" class="c_week_5" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>6</span>
    <input type="checkbox" class="c_week_6" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>7</span>
    <input type="checkbox" class="c_week_7" data-calculate="99">
  </div>
</form>

<div class="c_final_price_1_kid"></div>

2

Answers


  1. As per my understanding, You want to set/unset the data-calculate attribute value
    and calculate the sum dynamically based on the counts of the checked checkboxes. If Yes, Then you can simply achieve that by applying the click event listener on checkbox and do the manipulations.

    In below demo, By doing the inspect element You can see in developer console that data-calculate changes dynamically based on the count on select/unselect the checkboxes.

    Live Demo :

    let count = 0;
    
    document.querySelectorAll('input[type="checkbox"]').forEach(box => {
      box.addEventListener("click", (e) => {
        let sum = 0;
        box.checked ? count++ : count--;
    
        document.querySelectorAll('input[type="checkbox"]').forEach(box => {
          if (box.checked) {
            box.dataset.calculate = (count > 5 && count <= 7) ? (79.20) :
                ((count >= 3 && count <= 5) ? 84.15 : 99);
            sum = sum + parseFloat(box.dataset.calculate);
          }
        });
        // Assigning the sum of checked boxes into div inner text. 
        document.querySelector('.c_final_price_1_kid').innerText = sum.toFixed(2);
      })
    });
    <form id="form">
      <div class="c-checkbox-box">
        <span>1</span>
        <input type="checkbox" class="c_week_1" data-calculate="99">
      </div>
      <div class="c-checkbox-box">
        <span>2</span>
        <input type="checkbox" class="c_week_2" data-calculate="99">
      </div>
      <div class="c-checkbox-box">
        <span>3</span>
        <input type="checkbox" class="c_week_3" data-calculate="99">
      </div>
      <div class="c-checkbox-box">
        <span>4</span>
        <input type="checkbox" class="c_week_4" data-calculate="99">
      </div>
      <div class="c-checkbox-box">
        <span>5</span>
        <input type="checkbox" class="c_week_5" data-calculate="99">
      </div>
      <div class="c-checkbox-box">
        <span>6</span>
        <input type="checkbox" class="c_week_6" data-calculate="99">
      </div>
      <div class="c-checkbox-box">
        <span>7</span>
        <input type="checkbox" class="c_week_7" data-calculate="99">
      </div>
    </form>
    
    <div class="c_final_price_1_kid"></div>
    Login or Signup to reply.
  2. A possible solution.

    The limits and the multipliers are stored in an array.

    The count of selected checkboxes is computed by a DOM selector.

    It’s not clear if data-calculate is needed anymore with this solution, if not then remove the line of code where indicated.

    <script>
    
        const multipliers = [
            {from: 0, to: 2, mult: 99},
            {from: 3, to: 4, mult: 84.15},
            {from: 5, to: 7, mult: 79.20},
        ];
    
        const chkBoxQrySelector = '.c-checkbox-box > input[type="checkbox"]';
    
        document.addEventListener ('DOMContentLoaded', function () {
    
            const divResult = document.getElementsByClassName ("c_final_price_1_kid")[0];
    
            const chkBxsAll = document.querySelectorAll (chkBoxQrySelector);
    
            chkBxsAll.forEach (el => el.addEventListener ("click", () => {
    
                const chkBxsCnt = document.querySelectorAll (chkBoxQrySelector + ":checked").length;
    
                let total = 0;
    
                for (let m of multipliers) {
                    if (chkBxsCnt >= m.from  &&  chkBxsCnt <= m.to) {
                        chkBxsAll.forEach (el => {el.dataset.calculate = m.mult;}); // remove if data-calculate no more needed
                        total = (chkBxsCnt * m.mult).toFixed(2);
                        break;
                    }
                }
    
                divResult.innerText = total;
    
            }));
        });
    
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search