0

I am trying to get all "name" properties from checked checkboxes in NodeJS / Express, so i can then download the selected files from a directory on my server. The Frontend is written in EJS and creates a div, p and checkbox with name="name of file it belongs to" for each file present in the directory

<form method="POST" action="/download">
<% if(fileData.length > 0) { %>
  
  <% fileData.forEach(fileData => { %>
    <div>
      <p>
        <input type="checkbox" name="<%= fileData.name %>">
        <%= fileData.name %>
      </p>
    </div>
<%})%>
<%}%>
<button type="submit">Download selected</button>
Once the submit-button is clicked, a POST request is sent which is simply supposed to print all names of checked checkboxes
router.post('/download', function(req, res, next) {
 
//this function will later download the files

console.log(req.body); //this prints { 'selectedFile1.txt': 'on', 'selectedFile2.txt': 'on' }
});

How do i only get the names of the selected files from req.body, without the 'on'? Is there a different way of getting only the names of the selected checkboxes?

Mike
  • 23
  • 3

1 Answers1

0

You can use a for...in loop to iterate over the keys in the object like this:

const data = { 'selectedFile1.txt': 'on', 'selectedFile2.txt': 'on' }
let fileList = []
for (item in data) {
    fileList.push(item)
}
console.log(fileList)
Lxys
  • 16
  • 2