Node Express Jade - Checkbox boolean value

后端 未结 5 700
青春惊慌失措
青春惊慌失措 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:36

    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

提交回复
热议问题