Search code examples
node.jsejs

How to pass only those items in request body that have checkboxes checked in node.js and ejs templating engine


<form action="/attendence" method="post">
  <ul>
    <% for (let user of usersdata) { %>
    <li class="listItems">
      <a class="names" href="/users/<%=user.id%>"> <%=user.username%> </a>
      <input type="checkbox" class="checkbox" />      
    </li>
    <% } %>
  </ul>
</form>

I want that only those names are passed to /attendence api's request body that have checkboxes checked. I am working with nodejs and ejs templating engine.


Solution

  • Can add name and value attributes to checkbox input so that it can be passed when user submits the form:

    <form action="/attendence" method="post">
      <ul class="listItems">
        <% for (let user of usersdata) { %>
          <div class="div">
            <li >
              <input type="checkbox" class="checkbox" name="name" value= <%=user.username%> > 
              <label><a class="names" href="/users/<%=user.id%>"> <%=user.username%></a></label>
            </li>  
          </div>
        <% } %>
      </ul> 
      <div class="container"><button class="btn">SUBMIT</button></div>
    </form>
    

    the /attendence api looks like this:

    exports.addPresentUsers = (req, res, next) => {
      const presentUsers = req.body.name
      console.log(req.body.name)
      res.render('attendence', {
        presentUsers:presentUsers,
      });
    }