dimanche 17 janvier 2021

Only return value of textboxes that have their checkbox selected html

I have a form where the user can select items using checkboxes and enter the quantity of the item they want. Those values will be retrieved by the main.js and used to calculate the total sum of the nutrients for the items that were selected. The nutrients of each item is multiplied by their quantity before being added. However, the form returns the quantity of every item in the list instead of just the items that have their checkbox selected. How do I get the form to only return the quantity of items that have their checkbox selected?

app.post("/calculate", function (req, res) {
        let sqlquery = "SELECT SUM(?*calories) AS calories, SUM(?*carbs) AS carbs, SUM(?*fat) AS fat, SUM(?*protein) As protein, SUM(?*salt) As salt, SUM(?*sugar) As sugar FROM food_item WHERE name IN (?)";
        let sum = [req.body.qty, req.body.qty, req.body.qty, 
                   req.body.qty, req.body.qty, req.param('checkbox')];

        db.query(sqlquery, sum, (err, result) => {
            if (err) {
                return console.error(err.message);
            }else{
                res.send("The nutritional information and calorie count of "+ req.body.name + " is: " + JSON.stringify(result));
            }
        });
    });
<% availableFood.forEach(function(food_item){ %>
                <tr>
                        <td><input type="checkbox" name="checkbox[]" value= <%= food_item.name %>></td>    
                        <td><input id="qty" type="text" name="qty" value="1" style="width: 30px;"/></td>
                        <td><%= food_item.name %></td>
                        <td><%= food_item.typical_values %></td> 
                        <td><%= food_item.unit_of_the_typical_value %></td>
                        <td><%= food_item.calories %></td>
                        <td><%= food_item.carbs %></td>
                        <td><%= food_item.fat %></td>
                        <td><%= food_item.protein %></td> 
                        <td><%= food_item.salt %></td> 
                        <td><%= food_item.sugar %></td>
                </tr>
                <% }) %>    



Aucun commentaire:

Enregistrer un commentaire