Home > other >  Node.js/Express how to modify data obtained from checkbox form input
Node.js/Express how to modify data obtained from checkbox form input

Time:04-10

I have a list of input checkbox elements rendered with handlebars

<form method="POST" action='/processImages'>
                        <input type='checkbox' id='.DS_Store' name='.DS_Store' />
                            <p>.DS_Store</p>
                        <input type='checkbox' id='.localized' name='.localized' />
                            <p>.localized</p>
                        <input type='checkbox' id='Courses' name='Courses' />
                            <p>Courses</p>
                        <input type='checkbox' id='Home' name='Home' />
                            <p>Home</p>
                    
<input type="submit" value="run">
         

and i want to pass the names to the other function or render their names on other path With this code:

const processRouter = express.Router()

const processRouter = express.Router()
processRouter.post('/', async (req, res, next) => {
    const test =(req.body) 
    res.send(test)
})

app.use('/processImages', processRouter)

what im getting is:

{"Courses":"on","Home":"on"}

But i want to get just the names like {"Courses", "Home"} How to get rid of this "on" on each element, i'm assuming this is comming from input type checkbox.

I'm a beginner and i cant really understand how i should request only "names". Thanks

CodePudding user response:

It would not be possible to get {"Courses", "Home"} because this is invalid JSON format. You could however pass an array ["Courses", "Home"] through the request instead.

If the request that your form is sending is not something you want - consider writing your own onSubmit function to handle the AJAX call.


Nonetheless, is there a particular reason why you want to modify the request? You could parse the original format to result in what you want:

function iterate(input) {
    //Example input: {"Courses":"on","Home":"on"}

    const arr = [];

    Object.entries(input).forEach(function ([key, value], index) {
        console.log(key, value, index);
        if (value === "on")
            arr.push(key);
    });

    return arr;
}

console.log(iterate({ "Courses": "on", "Home": "on" }));
console.log(iterate({ "Courses": "on", "Home": "off" }));
  • Related