简体   繁体   中英

JavaScript how to take target value from one function and multiply by element value for which the checkbox has been checked

I've got two functions in my code. First function "addItem" gets the value of each individual input field as you click the arrow to increase/decrease the value. Second function "checkbox" verifies if the checkbox for has been enabled and if so adds the preset numerical value to a running total. What I'm having a hard time figuring out is how to take the input field value and multiple this by the checkbox value only if the checkbox is enabled adding it to my total. In the same way if I was to toggle checkbox to unchecked state I would remove that value from the total. Right now all its doing is when the checkbox is enabled it adds the checkbox value to the running total but it doesn't take into account the input field value when incremented or decremented. I would like it to dynamically calculate the total as the user changes input value and checkbox is enabled. I hope my explanation makes sense. My code is below. Of course there's additional stuff I'll be adding to the code but I'm not able to move forward unless I get this part working. Appreciate any feedback, thanks.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta class="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Restaurant | Online Menu</title>
    <link rel="shortcut icon" href="images/pngtree-green-leaf-icon-graphic-design-template-vector-png-image_3990501.jpg" type="image/x-icon" />
</head>
<div class= "nav-container">
    <nav id= "nav-bar">
        <a href= "index.html" class="active-link">Menu</a>
        <a href= "about.html">About</a>
        <a href= "Checkout.html">Checkout</a>
    </nav>
</div>
<button id= "remove-button">Remove All</button>
<div id= "item-container">
    <div class= "item-row">
        <input type= "checkbox" class= "checkbox" value= "10"> Item#1 $10 
        <input class= "counter-Items" type= "number" placeholder= "How many?" min= "1" max="10" style="width: 100px"> <button class= "remove-button">Remove</button> <br><br>
    </div>
    <div class= "item-row">
        <input type= "checkbox" class= "checkbox"  value= "8"> Item#2 $8
        <input class= "counter-Items" type= "number" placeholder= "How many?" min= "1" max="10" style="width: 100px"> <button class= "remove-button">Remove</button><br><br>
    </div>
    <div class= "item-row">
        <input type= "checkbox" class= "checkbox"  value= "6"> Item#3 $6
        <input class= "counter-Items" type= "number" placeholder= "How many?" min= "1" max="10" style="width: 100px"> <button class= "remove-button">Remove</button><br><br>
    </div>
    <div class= "item-row">
        <input type= "checkbox" class= "checkbox"  value= "4"> Item#4 $4
        <input class= "counter-Items" type= "number" placeholder= "How many?" min= "1" max="10" style="width: 100px"> <button class= "remove-button">Remove</button><br><br>
    </div>
    <div class= "item-row">
        <input type= "checkbox" class= "checkbox"  value= "2"> Item#5 $2
        <input class= "counter-Items" type= "number" placeholder= "How many?" min= "1" max="10" style="width: 100px"> <button class= "remove-button">Remove</button><br><br>
    </div>
    
<div id= "Total-Display">
    <h3 id="display-total">Current Total $
        <span id= "total-text"></span>
    </h3>
</div>
<button id= "btn-checkout">Checkout</button>
<script src= "functions.js"></script>
<body>
    <script src= "checkout-cart.js"></script>    
</body>
</html>

functions.js

const counterItems= document.getElementsByClassName('counter-Items')
const itemCheckBox =  document.getElementsByClassName('checkbox')
const removeBtn= document.getElementById('remove-button')
const btnCheckout= document.getElementById('btn-checkout')

let total = JSON.parse(localStorage.getItem('myValue'))
document.getElementById('total-text').innerText = total

retrieveDOMElementsState()

btnCheckout.addEventListener('click', onClickBtnCheckout)
function onClickBtnCheckout () {
    location.assign("/Checkout.html")
}

function retrieveDOMElementsState() {
    let saveChkBxState= JSON.parse(localStorage.getItem('saveChkBxState')) || []
    let inputFieldStoreValue= JSON.parse(localStorage.getItem('inputFieldStoreValue')) || []
    Array.from(itemCheckBox).forEach((itemCheckBoxItem, aIndex)=> {
        saveChkBxState.forEach((saveChkBxStateItem, bIndex) => {
            saveChkBxStateItem===true && aIndex===bIndex ? itemCheckBoxItem.setAttribute('checked', true) : false          
        })
        return retrieveDOMElementsState
})

    Array.from(counterItems).forEach((counterItemsItems, aIndex)=>{
        Array.from(inputFieldStoreValue).forEach((inputFieldStoreValueItem, bIndex)=>{
            aIndex===bIndex ? counterItemsItems.value= inputFieldStoreValueItem : false
        })
    })
}

Array.from(counterItems).forEach(item=> {
    item.addEventListener('change', onFieldChange) 
})

Array.from(itemCheckBox).forEach(item=> {
        item.addEventListener('change', onCheckBoxChange)
})

function onCheckBoxChange (e) {
    let checkbox = e.target
    let inputField = checkbox.nextElementSibling
    let price = checkbox.value
    let quantity = inputField.value
    calcTotal(price, quantity, e.target.checked)
    updateTotal() 
}

function onFieldChange(e){
    let saveChkBxState= Array.from(itemCheckBox).map(item=>{
        return item.checked
    })
    localStorage.setItem('saveChkBxState', JSON.stringify(saveChkBxState))

    let inputFieldStoreValue= Array.from(itemCheckBox).map(item=>{
        return item.nextElementSibling.value
     })
    localStorage.setItem('inputFieldStoreValue', JSON.stringify(inputFieldStoreValue))

    let inputField = e.target;
    let checkbox = inputField.previousElementSibling;
    let quantity = parseInt(inputField.value);
    if(quantity < 0 || quantity > 10){
      quantity = inputField.value = 0; 
    }
    inputField.value = quantity;
    if(checkbox.checked){
      let price = checkbox.value;
      let prevValue = inputField.prevValue;
      calcTotal(price, prevValue, false);
      calcTotal(price, quantity, true);
      updateTotal();
    }
    inputField.prevValue = quantity;
}

function calcTotal(price, quantity, add=true){
    price = price || 0;
    quantity = quantity || 0;
    if(add){
      total+=(price*quantity);
    }else{
      total-=(price*quantity);
    }
    localStorage.setItem('myValue', JSON.stringify(total))
}

function updateTotal(){
  document.getElementById('total-text').innerText = total;
}

removeBtn.addEventListener('click', onClickRemove)
function onClickRemove () {
    localStorage.clear()
    Array.from(itemCheckBox).forEach(item=>{
        item.checked= false
    })
    Array.from(counterItems).forEach(item=>{
        item.value= ''
    })
    total= 0
    updateTotal();
    
}

I have made some changes to the code to make it work as you expected.

CodePen Demo Link

 const counterItems= document.getElementsByClassName('counter-Items'); const itemCheckBox = document.getElementsByClassName('checkbox'); let total = 0; for (let i = 0; i < counterItems.length; i++) { counterItems[i].addEventListener('change', onFieldChange); } for (let i = 0; i < itemCheckBox.length; i++) { itemCheckBox[i].addEventListener('change', onCheckboxChange); } function onCheckboxChange(e){ let checkbox = e.target; let inputField = checkbox.nextElementSibling; let price = checkbox.value; let quantity = inputField.value; calcTotal(price, quantity, e.target.checked); updateTotal(); } function onFieldChange(e){ let inputField = e.target; let checkbox = inputField.previousElementSibling; let quantity = parseInt(inputField.value); //This condition is included in your code. if(quantity < 0 || quantity > 10){ quantity = inputField.value = 0; } inputField.value = quantity; if(checkbox.checked){ let price = checkbox.value; let prevValue = inputField.prevValue; calcTotal(price, prevValue, false); calcTotal(price, quantity, true); updateTotal(); } inputField.prevValue = quantity; } function calcTotal(price, quantity, add=true){ price = price || 0; quantity = quantity || 0; if(add){ total+=(price*quantity); }else{ total-=(price*quantity); } } function updateTotal(){ document.getElementById('total-text').innerText = total; }
 <nav> <button id= "Menu">Menu</button> <button id= "Cart">Cart</button> <button id= "About-us">About Us</button> </nav> <div id= "item-container"> <div class= "item-row"> <input type= "checkbox" class= "checkbox" value= "10"> Item#1 $10 | Add To Order <input class= "counter-Items" type= "number" placeholder= "How many?" min= "0" max="10" style="width: 100px"><br><br> </div> <div class= "item-row"> <input type= "checkbox" class= "checkbox" value= "8"> Item#12 $8 | Add To Order <input class= "counter-Items" type= "number" placeholder= "How many?" min= "0" max="10" style="width: 100px"><br><br> </div> <div class= "item-row"> <input type= "checkbox" class= "checkbox" value= "6"> Item#3 $6 | Add To Order <input class= "counter-Items" type= "number" placeholder= "How many?" min= "0" max="10" style="width: 100px"><br><br> </div> <div class= "item-row"> <input type= "checkbox" class= "checkbox" value= "6"> Item#3 $6 | Add To Order <input class= "counter-Items" type= "number" placeholder= "How many?" min= "0" max="10" style="width: 100px"><br><br> </div> <div class= "item-row"> <input type= "checkbox" class= "checkbox" value= "4"> Item#4 $4 | Add To Order <input class= "counter-Items" type= "number" placeholder= "How many?" min= "0" max="10" style="width: 100px"><br><br> </div> <div class= "item-row"> <input type= "checkbox" class= "checkbox" value= "2"> Item#5 $2 | Add To Order <input class= "counter-Items" type= "number" placeholder= "How many?" min= "0" max="10" style="width: 100px"><br><br> </div> <div id= "Total-Display"> <h3 id="display-total">Current Total (without taxes) $ <span id= "total-text">0</span> </h3> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM