Node Express Jade - Checkbox boolean value

后端 未结 5 539
青春惊慌失措
青春惊慌失措 2021-01-19 01:55

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.

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-19 02:44

    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

    
    

    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

提交回复
热议问题