首页 > 解决方案 > 获取勾选了 express js 复选框的项目的字段总和

问题描述

我有一个食品列表,我希望能够通过勾选相应的复选框然后计算它们的字段的总和来从列表中选择项目,例如我有名为卡路里、碳水化合物、脂肪、蛋白质、盐、糖和如果我在列表中选择两个项目并单击计算按钮,它将打印这两个项目的卡路里、碳水化合物、脂肪、蛋白质、盐、糖的总和。

<!doctype html>
<html>
<head>
<title>List foods page</title>
</head>
<body>
<h1> List foods page </h1>
<h3>Display all foods stored in the database including name, typical values, unit of the typical value, calories, carbs, fat, protein, salt, and sugar of the food item here:</h3>
<ul>
<% availableFood.forEach(function(food_item){ %>
        <form method="POST" action="/topic7/mid-term/calculate">
                <p><input type="checkbox" name="checkbox" value=<%= food_item.name %>>
                <input id="qty" type="text" name="qty" value="quantity"/>
                <%= food_item.name %>, <%= food_item.typical_values %>, 
                <%= food_item.unit_of_the_typical_value %>, <%= food_item.calories %>, 
                <%= food_item.carbs %>, <%= food_item.fat %>, <%= food_item.protein %>, 
                <%= food_item.salt %>, <%= food_item.sugar %></p>
        </form>
<% }) %>
<form method="POST" action="/topic7/mid-term/calculate">
        <input type="submit" value="Calculate sum" />
</form>
</ul>
</body>
</html>
app.post("/calculate", function (req, res) {
        let sqlquery = "SELECT SUM(calories, carbs, fat, protein, salt, sugar) FROM food_item WHERE name = ?";
        let sum = [req.body.checkbox];

        db.query(sqlquery, sum, (err, result) => {
            if (err) {
                return console.error(err.message);
            }else{
                res.send(" The nutritional information and calorie count of a recipe or a meal is: " + result);
            }
        });
    });

标签: node.jsexpress

解决方案


在 SQL 语句中使用集合而不是单个值,并与IN而不是比较=

总和需要单独计算。给他们起名字,AS使结果更容易阅读。

let sqlquery = "SELECT SUM(calories) AS calories, SUM(carbs) AS carbs, SUM(fat) AS fat FROM food_item WHERE name IN (?)";

推荐阅读