如何使用ejs获取node js中复选框的值?

问题描述 投票:0回答:3
javascript node.js checkbox ejs formidable
3个回答
0
投票

您可以使用括号符号来访问它

fields['hob[]']


0
投票
Sample form:
<!-- RADIO BUTTONS -->
   <p>
      <input class="with-gap" type="radio" name="gender" id="male" value="M" checked>
      <label for="male">Male</label>
   </p>
   <p>
       <input class="with-gap" type="radio" name="gender" id="female" value="F">
      <label for="female">Female</label>
   </p>

    <button type="submit" class="btn ">Sign up</button>

要从复选框中提取我们的值,我们可以通过 req.body.gender 来实现,M/F 的值将存储在 person 对象中

 let person = {
  gender: req.body.gender 
  }

0
投票

.ejs
文件中,我们将遵循。

<form action="/addhobby" method="POST">
   <div class="form-group">
        <h5>Hobbies</h5>
        <input type="checkbox" id="hobby" name="stuhobbies" value="sing"/> &nbsp;&nbsp;<strong>Sing</strong>&nbsp;&nbsp;
        <input type="checkbox" id="hobby" name="stuhobbies" value="guitarplay"/>&nbsp;&nbsp;<strong>GuitarPlay</strong>&nbsp;&nbsp;
        <input type="checkbox" id="hobby" name="stuhobbies" value="cricket"/>&nbsp;&nbsp;<strong>Cricket</strong>&nbsp;&nbsp;
        <input type="checkbox" id="hobby" name="stuhobbies" value="football"/>&nbsp;&nbsp;<strong>Football</strong>&nbsp;&nbsp;
  </div>
<button type="submit" class="btn btn-primary btn-md">
    Add
</button>

现在在操作或路线处理文件中我们执行以下操作。

const router = express.Router();
router.post('/addhobby', ensureAuthenticated,(req, res) => {    
    const { stuhobbies } = req.body;
    console.log(stuhobbies);
});
© www.soinside.com 2019 - 2024. All rights reserved.