Home > database >  Get Values of Selected Checkboxes in Express Data API?
Get Values of Selected Checkboxes in Express Data API?

Time:06-05

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" >
   <input type="checkbox" name="item2" value="2000" >
   <input type="checkbox" name="item3" value="3000" >

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

CodePudding user response:

Just use the OR operator to catch any missing values and set them to zero:

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

CodePudding user response:

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

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

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

total_cost: req.body.items.reduce((a,b) => a ( b), 0),
  • Related