简体   繁体   English

JavaScript 如何从一个 function 中获取目标值并乘以已选中复选框的元素值

[英]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.首先 function “addItem”在您单击箭头以增加/减少值时获取每个单独输入字段的值。 Second function "checkbox" verifies if the checkbox for has been enabled and if so adds the preset numerical value to a running total.第二个 function “复选框”验证复选框是否已启用,如果已启用,则将预设数值添加到运行总数中。 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.同样,如果我要将复选框切换为未选中的 state,我将从总数中删除该值。 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索引.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函数.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 CodePen 演示链接

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问已被Java复选框选中的表行中单元格的值? - How to access values of cells within a row of a table which has been checked by a checkbox in Javascript? 如果从javascript函数中的html文件中选中,则调用复选框值 - Call checkbox value if checked from html file in javascript function 跟踪已选中哪个CheckBox - Keep track of which CheckBox has been Checked 如何从使用 javascript 检查的复选框中获取值? - How to get value from checkbox checked using javascript? 如何通过javascript从复选框中仅获得可见和选中的值? - How to get value only visible and checked from checkbox via javascript? 如何从复选框数组中检查至少一个复选框,并且复选框中的文本区域不为空白,且其值为“ other”? - How to check at least one checkbox is checked from the array of checkboxes and the text area is not blank on checkbox with value “other” is checked? 检查后JavaScript隐藏一个复选框 - JavaScript Hiding a Checkbox after it has been checked 如何获取原版 JavaScript 中选中复选框的值? - How to get the value of checked checkbox in vanilla JavaScript? 如何计算在下一个td文本框中动态创建td具有相同值的复选框的计数? - How to get count of checkbox checked which has same value in next td textbox dynamically created td? 如何确定已从数组调用了哪个值以在另一个函数中使用? - How do I determine which value has been called from an array, to use in another function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM