Node Express Jade – checkbox布尔值

我正在使用Node + Express + Jade来渲染一些网页。 在表单上有2个checkbox。 当通过POST提交表单时,如果checkbox被选中,我得到req.body.checkbox1 -> 'on' ,如果没有选中,我得到req.body.checkbox1 -> undefined

有可能获取checkbox的值为truefalse

这是我的服务器端testing代码

 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('/'); }); 

和我的玉formstesting

 form(action='/config', method='post') input(type="checkbox", name="not_checked", checked=false) input(type="checkbox", name="checked", checked=true) input(type='submit') 

你可以尝试下面的玉forms

 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') 

值将是string,所以你必须parsing它。 如果checkbox没有检查属性,那么它将不会被包含在发布请求主体中。 所以在上面的表格中,只有checkbox会被发送到下面。

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

如果勾选两个checkbox,那么这两个值将按如下方式发送

 req.body : {"not_checked":"false","checked":"true"} 

您也可以添加validation反对未定义,每当没有勾选checkbox

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

我正在通过这个最近的一个项目…

这里是表格:

 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") 

然后在节点的javascript,他们可以通过每个的req.body.namefind。 如果其中一个框被选中,req.body.name将返回'on'。 如果一个框没有被选中,它们是未定义的。 所以一个三元语句可以用来创build一个新的对象,并将它们保存为一个数据库作为布尔值。

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

希望这有助于任何人前来。 一旦我想出来,我很高兴

我今天遇到这个问题,我有一个更清洁的解决scheme(对我来说):

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