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

Leverage nearby data using MediaSource

I am currently working on creating a local video player using nwjs (node-webkit). I have successfully played local files by setting their path as the src attribute of the video element. Now, I want to explore using MediaSource and potentially URL.createObj ...

Utilizing 'document.execCommand' for handling 'delete' key events in AngularJS

Here is a demo plunkr link that I have created to demonstrate the issue. I am looking to implement the strikeThrough command whenever there is a delete operation. For instance: If the user selects "Text" and presses the delete or backspace key, it should ...

Retrieving the JSON value from a data attribute and then locating the corresponding JSON key in a designated element within the DOM

I have an HTML element that contains a data attribute: <a href="#" data-trigger="{ "rem": "albatros", "ap":1 }'">Remove</a> <div data-container> <p>lorem ipsum<p> <p data-rem></p> </div> 1. So ...

Eliminate repeated entries in a drop-down menu and display them with commas in between

I am working with a list that contains various language combinations: German to English German to Spanish German to Chinese German to French English to Spanish English to French English to Greek English to Portuguese Does anyone have suggestions on how ...

`Datatables sorting feature for British date and time`

I'm currently attempting to organize a column in a table using the DataTables plugin that contains UK date and time formats such as: 21/09/2013 11:15 Implementing Ronan Guilloux's code: jQuery.extend( jQuery.fn.dataTableExt.oSort, { "uk_dat ...

The process of updating JSON data based on changes triggered by DOM events such as drag and drop

One challenge I am facing involves a Vue component used to render child components based on JSON data. The goal is to allow users to move and add components by dragging and dropping DOM elements on the page, using tools like jQuery draggable, droppable, an ...

Performing subtraction on two arrays in Javascript

Is there a way to eliminate all duplicate elements from one array list that are also present in another array list using the .filter() method of ES6 javascript? I am open to solutions in jQuery as well, but they must be compatible with IE11+ and Chrome fo ...

Instructions for making dropdown menus that dynamically reduce their options as you make selections:

I have an HTML form structured like this: Within the dropdowns, there is a uniform list of choices: Option 1, Option 2, Option 3. Users must select a value for each key, which currently functions correctly: Yet, I am seeking to enhance this functionality ...

What is the best way to attach a jQuery UI event handler to a button that has been dynamically generated?

Currently, I have a jquery ui modal dialog box form that inserts items into a table. A specific column in the table contains a button which serves as a link to edit the particular row. My goal is to attach an event handler to this button so that when a use ...

Issue encountered with Node Js: Unable to validate leaf signature while attempting to install the Express Framework

Looking to add the Express Framework to my application but encountering an error. I've attempted to configure Environment variables on my computer for npm using for both http and https. I have also tried running the following code: npm config set p ...

Having trouble implementing object type switching in Typescript

While in the process of developing an angular application, I stumbled upon a peculiar issue. Some time ago, I crafted this piece of code which performed flawlessly: selectedGeoArea: any receiveStoreEvent(event) { switch (event.constructor) { ca ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...

Can JQuery be used to identify the CSS styles applied to selected elements?

Highlight the text by selecting it and clicking a button. If the text is already highlighted, clicking the button should make the selected text return to normal. Can this be achieved using jQuery and a single button? Is it possible to identify the CSS st ...

Embedding HTML Tags within an array element

The task at hand involves adding an HTML element from Array Value to the Document Object Model template: { 0: { h1: '<h1>Hi</h1>' }, 1: { h2: '<h2>Hi</h2>' }, 2: { h3: &a ...

Efficiently map nested properties of this.props within the render method

When working in the render() method, I find myself passing numerous variables around. The recommended best practices suggest setting up variables before the return <div>...etc</div statement like this: const { products: mainProducts, ...

Node.js app on Google App Engine experiencing memory leaks when running a basic pubsub application, leading to surpassing the soft private memory limit

My experience with developing a simple appEngine using pubsub app has led me to some concerning observations. Upon reviewing the appEngine logs, I noticed a constant increase and drop in memory usage that repeats itself. Upon closer inspection of the logs, ...

Adding a JavaScript variable into a Django template tag

This particular situation has been presenting a challenge for me. So far, I have been using query parameters instead of a variable within the {% url %} tag. However, I can't help but wonder if there is a way to achieve this: I am interested in includ ...

The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the ...

Getting rid of a texture in three.js

I am attempting to deallocate a texture once it has been loaded in three.js. The texture is loaded using var tex = THREE.ImageUtils.loadTexture("image.png"); and it is being displayed correctly. However, when I attempt to use: tex.dispose(); I consist ...

Having trouble establishing a connection to the FTP server through the "ftp" package provided by npm

Attempting to establish a connection to a Secured FTP server using the "ftp" package. When connecting to an unsecured server, everything functions as expected with all events firing and content being displayed. However, upon trying to connect to a server ...