How to get values of checkbox in node js using ejs?

2 min read 06-10-2024
How to get values of checkbox in node js using ejs?


Getting Checkbox Values in Node.js with EJS: A Simple Guide

Need to capture user selections from checkboxes in your Node.js application using EJS templates? It's easier than you think! This article will guide you through the process, providing clear explanations and code examples.

The Challenge: Capturing Checkbox Data

Imagine you're building a simple survey using Node.js and EJS. You want to let users select multiple options from a list of choices presented as checkboxes. The challenge lies in how you retrieve those selected values from the user's form submission.

The Solution: Combining EJS and Node.js

Here's a breakdown of the approach:

1. EJS Template:

First, let's create our EJS template (e.g., survey.ejs):

<!DOCTYPE html>
<html>
<head>
  <title>Survey</title>
</head>
<body>
  <h1>Survey Form</h1>
  <form action="/submit-survey" method="POST">
    <p>What are your favorite hobbies?</p>
    <label for="hobby1">Reading</label>
    <input type="checkbox" name="hobbies" id="hobby1" value="Reading">
    <br>
    <label for="hobby2">Hiking</label>
    <input type="checkbox" name="hobbies" id="hobby2" value="Hiking">
    <br>
    <label for="hobby3">Coding</label>
    <input type="checkbox" name="hobbies" id="hobby3" value="Coding">
    <br>
    <button type="submit">Submit</button>
  </form>
</body>
</html>

2. Node.js Server-Side Logic:

Now, let's handle the form submission in our Node.js server (app.js):

const express = require('express');
const app = express();
const ejs = require('ejs');

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.render('survey');
});

app.post('/submit-survey', (req, res) => {
  const hobbies = req.body.hobbies;

  if (Array.isArray(hobbies)) { // Handle multiple selections
    console.log('Selected Hobbies:', hobbies);
    res.send(`You selected: ${hobbies.join(', ')}`);
  } else { // Handle single selection (if only one checkbox is selected)
    console.log('Selected Hobby:', hobbies);
    res.send(`You selected: ${hobbies}`);
  }
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Explanation:

  • EJS Template: The template uses the name attribute (hobbies) for all checkboxes to group them together. The value attribute holds the individual option's value.
  • Node.js Server:
    • We receive the submitted data from the form using req.body.hobbies.
    • Since multiple checkboxes can be selected, req.body.hobbies will be an array. We use Array.isArray(hobbies) to check for this.
    • If it's an array, we display all selected values. If not, we display the single selected value.

Key Points:

  • Checkbox Name: Use the same name attribute for all checkboxes to allow multiple selections.
  • Array Handling: The server-side code should handle the req.body.hobbies as an array, even if only one checkbox is selected.
  • EJS Rendering: EJS templates are essential for creating dynamic HTML with server-side data.

Extending the Example:

You can extend this example by:

  • Storing Selected Data: Save the chosen hobbies to a database for later use.
  • Dynamic Content: Populate the checkboxes with data retrieved from a database.
  • Validation: Implement server-side validation to ensure user input conforms to your requirements.

Conclusion

Working with checkboxes in Node.js and EJS is straightforward. By understanding the core principles of grouping checkboxes with the same name, handling form submissions, and using EJS for dynamic content, you can easily capture user selections from your web forms.