Node Express Jade - 复选框布尔值 [英] Node Express Jade - Checkbox boolean value

查看:25
本文介绍了Node Express Jade - 复选框布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Node+Express+Jade to render some webpages. On a form there are 2 checkboxes. When the form is submitted through POST, if the checkbox is checked, I get req.body.checkbox1 -> 'on', if isn't checked, I get req.body.checkbox1 -> undefined

是否可以将复选框值设为 truefalse ?

Is possible to get checkbox value as true or false ?

这是我的服务器端测试代码

Here's my server side test code

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

推荐答案

你可以试试下面的玉形吗

Can you try the following jade form

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

该值将是字符串,因此您必须对其进行解析.如果复选框没有选中属性,则它不会包含在发布请求正文中.所以在上面的表格中,只会发送选中的复选框,如下所示.

The value will be string, so you have to parse it. If the checkbox does not have checked attribute then it would not be included in the post request body. So in the above form, only the checked checkbox will be sent see below.

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

如果您勾选两个复选框,则两个值都将如下发送

If you tick both checkboxes then both values will be sent as below

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

你也可以添加对未定义的验证,只要没有勾选复选框

You can also add validation against undefined, whenever no checkbox is ticked

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

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

这篇关于Node Express Jade - 复选框布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆