Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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'),
about 4 years ago · Juan Pablo Isaza Relatório

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,
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda