Using checkboxes in an Express application

Currently, I am working on the task of parsing checkbox values into an array using express/ejs.

Users are required to fill out a form and select checkboxes as shown below: Answer: Checkbox:

The goal is to create two arrays from the input data:

answer = ["string 1", "string 2", "string 3", "string 4"] checkbox = [checked, unchecked, unchecked, unchecked]

The issue is that express only processes checked checkboxes and ignores unchecked ones (resulting in checkbox = "checked" only).

How can I make express log the "unchecked" values too? I have thought about setting the value to true/false depending on whether the checkbox is checked, but I am unsure how to handle this in ejs.

Thank you!

JS

router.post(`/`, (req, res) => {
    console.log(req.body);
    res.redirect(`/`);
})

EJS

<form action="/question" method="post">
        <label for="sessionName">Session Name</label><input type="text" name="sessionName">
        <div class="question">
            <label for="question">Question: </label><input type="textarea" name="question">
            <ul>
                <li><label for="answer">Answer 1: </label><input type="textarea" name="answer"><input type="checkbox" name="test" value="1"></li>
                <li><label for="answer">Answer 2: </label><input type="textarea" name="answer"><input type="checkbox" name="test" value="1"></li>
                <li><label for="answer">Answer 3: </label><input type="textarea" name="answer"><input type="checkbox" name="test" value="1"></li>
                <li><label for="answer">Answer 4: </label><input type="textarea" name="answer"><input type="checkbox" name="test" value="1"></li>
            </ul>
        </div>
        <input type="submit" name="" value="Create Session">
    </form>

Answer №1

When sending the form to the node server, only the checked values will be included. This means that Express will not have any information about unchecked values or their corresponding strings or labels.

To address this limitation, you may need to implement your own solution using hidden inputs and updating values right before submission (e.g., form.onsubmit = ...) to generate the arrays you require.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to troubleshoot the logic issue in the loop for my simple login interface

I have been able to successfully implement code that detects when a user enters an incorrect username or password, as well as granting access when the correct credentials are provided initially. However, there seems to be a logic error in my loop that prev ...

Can you explain the significance of the "@" symbol prefix found in npm package names?

While reading through the Angular Component Router documentation, I came across an npm command that caught my attention: npm install @angular/router --save I'm puzzled by the meaning of @angular/router. Is this entire string a package name? If so, ...

Utilizing Environment Variables Across Multiple Files in Node.js with the Help of the dotenv Package

I am currently developing a basic application that utilizes the Google Maps API and Darksky API. To keep my API keys secure, I have implemented dotenv for key management. I have successfully integrated dotenv in my main file (app.js), but now I need to a ...

Comparing two datetime objects with time zone offsets in JavaScript: How to determine if one is greater than or less than the other?

So I'm faced with a situation where I need to compare two dates where the first date is 05.01.2008 6:00 +5:00 and the second date is 05.01.2008 7:00 +5:00 I'm struggling to find a way to convert these datetimeoffsets into a specific forma ...

Issue with Google map displaying incorrectly when attempting to print

I am experiencing an issue with printing a Google Map using the JavaScript API V3. The problem I am facing is that the map is split into two parts, with the top and bottom sections overlapping each other. Here is the code snippet: var geocoder; var ...

The server opts to download source code rather than executing it

Whenever I utilize node.js and attempt to access localhost:8080, which is the port I am currently listening on, the source code downloads instead of displaying the website. The command I am using to run the app is: node name.js This issue started occurr ...

How can you verify the correctness of imports in Typescript?

Is there a way to ensure the validity and usage of all imports during the build or linting phase in a Typescript based project? validity (checking for paths that lead to non-existent files) usage (detecting any unused imports) We recently encountered an ...

Searching and adding new elements to a sorted array of objects using binary insertion algorithm

I'm currently working on implementing a method to insert an object into a sorted array using binary search to determine the correct index for the new object. You can view the code on codesanbox The array I have is sorted using the following comparis ...

The application encountered an issue when attempting to assign a value to the property 'username' of a

Encountering an issue where a logged in user is attempting to update their account username but facing an error. I am unable to determine why some users (about 1 out of 20) are experiencing difficulty in finding the current user even though they can only a ...

Assign a value to the Angular directive for the SharePoint People Picker

In my create form, I have successfully used a directive to capture and store values in SharePoint via REST. The directive I am using can be found at this link. Within my HTML, I am implementing the directive like this: <sp-people-picker name="CC" id=" ...

A guide to using JavaScript to create a button that can dynamically change stylesheets

Just a heads up, I'm not using classes in this particular scenario. Can't seem to find the answer to this exact question. With javascript, how can I code a button to switch stylesheets every time it's clicked? I've experimented with d ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function. button.tsx {((this.test1) || this.selectedExistingId) && ...

End: unrelated, lacking responses

I have a question I'd like to discuss: Whenever I utilize the following code snippet: async function createNewElement(req,res){ const start1 = new Date().getTime(); console.log("start time 1 ", start1) await new Promise((resolve) => setT ...

Error message: When accessing react-native camera roll, the message "this.state.photos is not a valid object" appears

Encountering an error while attempting to implement camera roll functionality in my demo app. The error states, "null is not an object (evaluating 'this.state.photos')" View iOS Error Message. I am a beginner developer working on my first react-n ...

Vanishing Act: React-js MUI Tooltip vanishes upon clicking

The standard behavior of the MUI Tooltip is as follows:
 If the button/icon to trigger a tooltip is not in focus, the tooltip will not disappear when clicking directly on the popper. However, if the button/icon is focused, the tooltip will disappear upo ...

A method for dividing a string into separate characters and organizing them into an array of JSON objects

I have a collection of JSON objects with a fixed key 'type' and additional keys based on the type. Here is an example of how it looks: theArray = [ { "type": "text", "text": "= SUM(" ...

Error: Unable to access property of an undefined value (ExpressJS/POST)

I have gone through all the similar questions but none of the solutions are working for me. I am facing an issue with my node js app where I am unable to print the input text from a form while using body-parser. Here is my index.ejs file: <fo ...

What is the best way to display an HTML page in the bottom right corner instead of within a div?

I am trying to display the content of an HTML page in the bottom right corner of another page using my JavaScript script. However, I do not want to insert a div into the page and then load the content inside it. Instead, I am looking for an alternative way ...

Looking to save an image using a form in MongoDB?

There is a database file on MongoDB Atlas called food_items. I want to upload an image and data from the frontend form to there. Error saving food item: TypeError: global.food_items is not a constructor at uploadFoodItem (D:\ecom2 - Copy\backend ...