简体   繁体   中英

Get Values of Selected Checkboxes in Express Data API?

So I have multiple input checkboxes, but I want to only get the data if I select the checkbox for my express post function

So here is 3 checkboxes I have with different values of 1000,2000, & 3000

   <input type="checkbox" name="item1" value="1000" class="food">
   <input type="checkbox" name="item2" value="2000" class="food">
   <input type="checkbox" name="item3" value="3000" class="food">

Now in express post function when I submit my form, I can get my data like this

const response = await client

    {
        other_data: 'other data from my forms'
        total_cost: parseInt(req.body.item1) + parseInt(req.body.item2) + parseInt(req.body.item3),
    
    }

The problem is when I submit my form, it will only calculate the total if I select all 3 input checkboxes and hence display the total_cost of 6000

But if I only click on one input checkbox, then submit my form it will show the value of 0 even though I clicked one input 1 with a value of 1000.

How do I add my data in express so that it will display my input checkbox value based on the input I clicked on? Because if I had 100 inputs, then manually adding them seems inefficient

只需使用 OR 运算符捕获任何缺失值并将它们设置为零:

total_cost: parseInt(req.body.item1||'0') + parseInt(req.body.item2||'0') + parseInt(req.body.item3||'0'),

To better manage the input data on the backend, give each checkbox the same name attribute.

<input type="checkbox" name="items" value="1000" class="food">
<input type="checkbox" name="items" value="2000" class="food">
<input type="checkbox" name="items" value="3000" class="food">

Then on the backend, you can just add up the values as such:

total_cost: req.body.items?.reduce((a,b) => a+(+b), 0) || 0,

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