Read checkbox value Node JS + Express + Jade

眉间皱痕 提交于 2019-12-10 18:09:46

问题


I'm inserting web page values into a Mongo DB, Im using Node JS + Express + Jade. and I need to insert True or False, depending if checkbox is enabled or not.

In my router.js I have the following:

app.get('/notification', function(req, res) {
    res.render('notification', {  title: 'Nueva notificacion', notifications : NT });
});

app.post('/notification', function(req, res){
    console.log('Adding new notification');
    AM.addNewNotification({
        name    : req.param('name'),
        notification : req.param('notification'),
        active  : req.param('active')
    }, function(e){
        if (e){
            res.send(e, 400);
        }   else{
            res.send('ok', 200);
        }
    });
});

In my view I have the following:

.controls
                    label#active-me.checkbox Active
                        input(type="checkbox", name="active", id="active",checked='checked')

But I can't insert it, looks like value is not taken. Only name and notification values (Text) are inserted.

{ "name" : "Goodbye world", "notification" : "Short Message Service", "_id" : ObjectId("5298f603bd07b80376000005") }

Any suggestions?

Thanks


回答1:


Browsers add checkbox's value to requests when the box is checked. There are several ways to handle this behavior on the server.

The most obvious is to treat the absence of parameter as its being false.

Another way is what Rails do: add a hidden input with the same name and zero value before the checkbox. In your case:

.controls
  label#active-me.checkbox Active
  input(type="hidden", name="active", value=0)
  input(type="checkbox", name="active", id="active",checked='checked')

In addition, your code in app.post should probably use req.body, instead of req.param.




回答2:


.controls label#active-me.checkbox Active input(type="checkbox", name="checkedboxes[]",checked='true')

This will give you an array of checked boxes in req.body



来源:https://stackoverflow.com/questions/20965775/read-checkbox-value-node-js-express-jade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!