Marked checkboxes and Node.js

I'm having trouble grasping the concept of using HTML checkboxes with Node.js and Express. I have a basic form in EJS and before diving deeper into the backend logic, I want to ensure that the correct values are being retrieved. Despite my efforts to find help elsewhere, every console.log statement is returning false instead of true when the checkbox is selected. I suspect it might be an issue with my Express backend rather than the form itself. Any assistance would be greatly appreciated.

EJS

<form action="/results" method="POST">
    <ul>
        <li>
            <label for="citysearch">City Name</label>
            <input type="text" name="citysearch" id="citysearch" placeholder="e.g. Los Angeles">
        </li>
        <li>
            <label for="Celcius">Celcius?</label>
            <input type="checkbox" name="celcius" id="celcius" checked="true">
        </li>
    </ul>
    <button type="submit">Submit</button>
</form>

Express/Node

app.post('/results', function(req, res){

    var checked = req.body.checked

    if (checked == "true") {
        console.log("true");
 } else {
        console.log("false");
    }
});

Answer №1

Your request body does not contain a property named checked. Instead, it has two properties: citysearch and celcius. To add a value to your checkbox, do the following:

<input type="checkbox" name="celcius" id="celcius" checked="true" value="true">

In your controller, use the following code snippet:

if (req.body.celcius) {
        console.log("true");
 } else {
        console.log("false");
 }

Keep in mind that if you leave the checkbox unchecked, only the citysearch property will be present in your req.body as unchecked checkboxes are not included in the data sent to the controller.

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

AngularJS - Sending configuration values to a directive

I'm trying to figure out how to pass parameters (values and functions) to an Angular directive. It seems like there should be a way to do this in Angular, but I haven't been able to locate the necessary information. Perhaps I'm not using th ...

Content in React Router may fail to load when refreshing the page, navigating forward, or manually

I recently started using React and I'm getting familiar with React Router. I divided my application into two main routes because each uses a different style: the Splash path is for when the user first enters, which contains the Splash screen, Login, a ...

How can I deliver assets in React without the PUBLIC_URL showing up in the path?

I have set up a portfolio website that includes my resume. I am trying to make it so that when someone visits the route http://localhost:3000/resume.pdf, they can view my resume directly. The resume.pdf file is located in my public folder. However, instead ...

Tips for preventing the use of eval when invoking various functions

Here's a snippet of code I've been using that involves the use of eval. I opted for this approach as it seemed like the most straightforward way to trigger various factory functions, each responsible for different web service calls. I'm awa ...

Calculating values within dynamically generated elements requires utilizing JavaScript to target and extract the

I am working on creating input fields inside an HTML table using Vue.js. On click of a button, I want to perform some calculations based on the input values. However, it seems that the calculations are not happening as desired. What I have attempted so fa ...

conceal parent window element upon clicking an image within an iframe

I'm facing a challenge with hiding certain buttons in a parent window when opening a modal by clicking an image inside an iframe. Below is the code snippet that I am using: In the parent window - <iframe id="gallery" src="links/gallery.html" wid ...

Using a loop to iterate through a multidimensional array in Node.js or JavaScript, creating additional data and adding new key-value pairs

Here is an array of objects showcasing different intents and results : var finalresult = [{ "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)", "data": [{ "intent": "delivery", "result": [{ "h ...

At times, Vue.js may encounter difficulties when attempting to load a component

Recently, a strange issue has been occurring in my production code. Although nothing has been changed, I am now receiving reports that occasionally a template fails to load causing the page to crash. I am currently using vue 2.16. The error messages being ...

Unable to iterate through nested arrays in Contentful mapping

I am facing an issue while trying to map further into the array after successfully retrieving data from Contentful. The error message field.fields.map is not a function keeps popping up and I can't figure out what I'm doing wrong. export defau ...

Is it permissible to call next within a helper function?

I am currently working on setting up a basic system to handle user-input errors and prevent propagation in express. Here is what I have so far: routingFunction = (req, res, next) { //setting up a test in express-validator var test = req.assert('a ...

Integrating objects into the <select> element through the combination of C#, JavaScript, and HTML connected to a SQL

Can someone assist me in resolving this issue? I am trying to populate an HTML element with database fields using C# and JavaScript, but so far my code is not producing any output. I have also attempted to include a button that calls the "loadGrp" function ...

tips for patiently awaiting an ajax response before setting the object

I am currently working on a basic todo app using React. Initially, everything was running smoothly when I stored my data in a pre-defined object. However, now that I am retrieving my data from a link (rest) using AJAX, I seem to be encountering some issues ...

The item is not functioning properly as intended

After delving into the concepts of prototype and proto, I believed that I had grasped the concept. However, something doesn't seem to add up. Can someone shed light on why directly accessing an Object like this does not yield the desired outcome? fun ...

Verifying Value Equality in all Documents with MongoDB

One feature on my website allows users to input a number into the field labeled subNum in a form. Upon submission of the form, I need to validate whether the entered value already exists within any existing document. This validation process is implemented ...

What is the best way to create a sliding animation on a div that makes it disappear?

While I may not be an expert in animations, I have a question about sliding up the "gl_banner" div after a short delay and having the content below it move back to its original position. What CSS properties should I use for this animation? Should I use css ...

Inject JavaScript Object Information into Bootstrap Modal

After iterating through each object and assigning its data to an individual div along with a button, I encountered an issue. When testing the buttons, I noticed that only the last object's data was displayed in all of the modal windows. Any suggestion ...

When utilizing the map function to render an array of objects, React encounters an error

My React application is throwing an error when using the map function. Interestingly, the code works fine in a sandbox environment. Error: ENOSPC: System limit for number of file watchers reached, watch. After creating a new React project, the error dis ...

RedisClient: The function redisClient.auth() returns an error message stating that it cannot destructure the property 'username' of 'undefined' because it is not defined

Attempting to establish a connection to a Redis service using my Node.js code in production: const { createClient } = require('redis'); const redisClient = createClient({ url: config.redis.url, }); const connectRedis = async () => { try ...

Ways to monitor and measure clicks effectively

Within my website, I have a table element with one column and numerous rows. Each row serves as a hyperlink to an external shared drive. <tr><td ><a href="file://xxx">Staff1</a></td></tr> <tr ><td ><a h ...

Utilizing Jquery to Pass an Optional Function to Another Function

I am currently working on a function that utilizes AJAX to submit data and then displays a dialog indicating whether the process was successful or not. Everything seems to be functioning smoothly, but I now want to add the capability of passing an addition ...