Node Express Jade - 复选框布尔值

5
我正在使用Node+Express+Jade来渲染一些网页。在一个表单中有2个复选框。当表单通过POST提交时,如果复选框被选中,我会得到req.body.checkbox1 -> 'on',如果没有被选中,我会得到req.body.checkbox1 -> undefined
是否可能获取复选框的值为truefalse
这是我的服务器端测试代码。
var bodyParser = require('body-parser');
var express = require('express');

var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/webroot'));
app.set('views', __dirname + '/view');
app.set('view engine', 'jade');
app.listen(3001);
app.get('/', function (req, res) {
    res.render('test');
});

app.post('/config', function (req, res) {
    console.log(req.body.t);
    console.log(req.body.f);
    res.redirect('/');
});

我的玉表单测试
form(action='/config', method='post')
    input(type="checkbox", name="not_checked", checked=false)
    input(type="checkbox", name="checked", checked=true)
    input(type='submit')
6个回答

9
我是最近为一个项目在处理以下内容:
这里是表格:
form(action='/survey/submission/test/config', method='post')
    input(type="checkbox", name="1")
    input(type="checkbox", name="2")
    input(type="checkbox", name="3")
    input(type="submit")

然后在Node.js中,可以通过req.body.name找到这些复选框的值。如果其中一个复选框被选中,req.body.name将返回' on '。如果没有选中,它们将是未定义的。因此,可以使用三元运算符创建一个新对象,并将它们保存为布尔值到数据库中。

object = {
    first: req.body.1 ? true : false,
    second: req.body.2 ? true : false,
    third: req.body.3 ? true : false
};

希望这能帮助到其他人。一旦我弄清楚了,我就很高兴了。

4
还有一种写法可以减少代码量:first: !!req.body[1] 以此类推。通过逻辑非运算符,我们可以得到表达式的相反布尔值,并通过另一个逻辑非运算符将其反转回来。结果与答案中的代码相同。 - 1valdis

4

今天我遇到了这个问题,但是我有一个更简洁的解决方案(适合我):

function(req, res){
   req.body.field = Boolean(req.body.field)
}

1
你的回答看起来像是一个通用的中间件。注册这样的中间件将是一个巨大的错误。你能否编辑它,使其更具体地针对问题? - François Zaninotto
2
我不明白,真正的问题是:“如何从Node/Express复选框获取布尔值”,所以我的答案是正确的,对吗?如果你认为不是,请不要点赞。 - A. Moynet

3
你能尝试下面的Jade表单吗?
form(action='/survey/submission/test/config', method='post')
  input(type="checkbox", name="not_checked", value="false")
  input(type="checkbox", name="checked", checked, value="true")
  input(type='submit')

该值将为字符串,因此您需要解析它。如果复选框没有checked属性,则不会包含在POST请求正文中。因此,在上面的表单中,只有选中的复选框将被发送,请参见下文。

req.body : {"checked":"true"}

如果您勾选两个复选框,则两个值将如下发送。
req.body : {"not_checked":"false","checked":"true"}

您可以添加针对未定义的验证,即在没有选中复选框时。
   if(req.body.not_checked) {
      console.log('not checked : ' + req.body.not_checked);
    }

    if(req.body.checked) {
      console.log('checked : ' + req.body.checked);
    }

谢谢你的提示,使用单选框组可能可以达到我想要的效果。我会加入一个带有两个按钮(真和假)的单选框组,而不是复选框。 - Matheus Vellone

1

我解决了这个问题。首先,我想说我使用的是NodeJS上的ExpressJS,使用jade/pug模板引擎(+bootstrap 4.1)。

div.form-group.form-check
   if customer.status
       input#checkbox.form-check-input(type="checkbox" name="status" value="true" checked)
   else
       input#checkbox.form-check-input(type="checkbox" name="status" value="false")

NodeJS - customer.js
// Update: Update a customer that given id
router.post('/update/:id', (req, res, next) => {

    const customerId = req.params.id;
    // let { name, email, city, country, status } = req.body;

    // Convert value to Boolean
    req.body.status = Boolean(req.body.status); 

    console.log(req.body); // true | false

    Customer.updateOne({ _id: customerId }, req.body).then( /* ... */)

}

另一个简单的例子:

html、jade或pug文件

<input type="checkbox" name="status" value="false" checked>

NodeJS JavaScript文件

app.post('/update/:id', (req, res, next) => {

     // Firstly, we can try it
     console.log(req.body.status); // Output: undefined

     // Then we should convert this value to Boolean
     req.body.status = Boolean(req.body.status);

     console.log(req.body.status) // Output: false or true
}

希望我的解决方案能对你有所帮助


0
<form>
    <input type="checkbox" name="imp" value=false>
</form>

let impMarks  ; // 

app.post("/", function(req, res) {
    impMarks =  Boolean(req.body.imp);
    console.log(**impMark**); // the output will be true(if checked) / false 
});

请不要仅仅发布代码作为答案,还要提供解释您的代码是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Tyler2P

0
如果您的默认值为false,则对我来说,此解决方案似乎是最直接的。 首先使用您的DB / ORM设置默认值。 我正在使用Mongoose,因此在模型文件中它是:
published: { type: Boolean, default: false },

然后在表单输入元素中将值设置为true:

<input type="checkbox" name="published" id="published" value=true>
<label for="published">Publish</label>

取消勾选它将提交一个空值,该值默认为false。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接