Node Express Jade - Checkbox boolean value
Asked Answered
H

6

5

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

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

And my Jade form test

form(action='/config', method='post')
    input(type="checkbox", name="not_checked", checked=false)
    input(type="checkbox", name="checked", checked=true)
    input(type='submit')
Hooghly answered 25/8, 2015 at 11:58 Comment(0)
H
3

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);
    }
Hepatitis answered 25/8, 2015 at 12:13 Comment(1)
Thanks for the tip, this idea with a radio group may work something like I want. Instead of a checkbox, i'll add a radio group with 2 buttons (true and false).Hooghly
C
9

I was working through this recently for a project...

Here is the form :

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

then in the node javascript they can be found through the req.body.name of each. req.body.name will return 'on' if one of the boxes if checked. if a box is not checked, they are undefined. so a ternary statement can be used to create a new object and save them to a db as a boolean value.

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

Hope this helps anyone else coming along. I was happy once I figured it out

Constantan answered 5/5, 2016 at 22:44 Comment(1)
There's also a way to write less code: first: !!req.body[1] and so on. With the one logical not operator we get the opposite boolean value of expression and with the other one we reverse it back. The result is the same as of the code in the answer.Hostler
E
4

I have meet this problem today and I have a solution more clean (for me):

function(req, res){
   req.body.field = Boolean(req.body.field)
}
Eject answered 13/6, 2017 at 15:35 Comment(2)
Your answer looks like a generic middleware. Registering such a middleware would be a huge mistake. Could you edit it to make it more specific to the question?Dawndawna
I don't understand, the real question is: "How to get a boolean value from checkbox on Node/Express", so my answer is correct no ? If you think not, juste dont up.Eject
H
3

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);
    }
Hepatitis answered 25/8, 2015 at 12:13 Comment(1)
Thanks for the tip, this idea with a radio group may work something like I want. Instead of a checkbox, i'll add a radio group with 2 buttons (true and false).Hooghly
C
1

I solved this problem. Firstly I just want to say that I use jade/pug template engine (+bootstrap 4.1) with ExpressJS on NodeJS.

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( /* ... */)

}

Another Simple Example:

html, jade or pug file

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

NodeJS Javascript file

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
}

I hope my solutions help you

Chiffonier answered 23/1, 2020 at 15:15 Comment(0)
B
0

If your default value is false then this solution seems the most straight-forward to me. First set a default with your DB/ORM. I'm using Mongoose so in the model file it's:

published: { type: Boolean, default: false },

Then in the form input element set the value to true:

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

By unchecking it you'll submit an empty value which defaults back to false.

Brochette answered 16/9, 2019 at 0:59 Comment(0)
D
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 
});
Davisdavison answered 19/5, 2021 at 10:48 Comment(1)
Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.Asshur

© 2022 - 2024 — McMap. All rights reserved.