Node Express Jade - Checkbox boolean value

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

    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);
        }
    

提交回复
热议问题