I am creating a To-Do-List, using express and ejs. I want to add functionality in my To-Do-List that when I check the checkbox, I want that particular content striked-through.
Firstly, I tried getting the value of the checkbox through body-parser, save it in a variable and then pass it on to my index.ejs file. I tried using the variable on in the EJS file but it didn’t work.
I eventually console logged the variable and then I saw that the value which was display was "undefined".
import express from "express";
import bodyParser from "body-parser";
const app = express();
const port = 3000;
const Item = [];
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.get('/',(req,res)=>{
res.render("index.ejs",{Item})
})
app.post('/submit',(req,res)=>{
const {Item: newData} = req.body;
const checked = req.body["check"];
Item.push(newData)
res.render("index.ejs",{Item,checked})
console.log(checked)
})
app.listen(port,()=>{
console.log("Server is running on port",port);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<title>ToDoList</title>
</head>
<body>
<div class="container">
<form action="/submit" method="POST">
<input
type="text"
placeholder="New Item"
name="Item"
class="input-area"
required
/>
<input type="submit" class="btn" value="Add" />
</form>
</div>
<% Item.forEach(item => { %>
<div class="container-2">
<input type="checkbox" class="checkBox" name="check" required />
<%= item %>
</div>
<% }) %>
</body>
</html>
2
Answers
I find your code hard to follow because you’ve named everything a variable of "Item". You should try to distinctly name things to avoid confusion.
That said, in your HTML, "Item" is an object (Bound on line 18) of the first block. This object should contain the boolean value you need under the key of ‘checked’.
In your
forEach
on the input element in the HTML, you should be able to do something like<%= item.check ? 'checked' : ''%>
which basically means, if item.check exists and has value/is true, then add ‘checked’ to the HTML input element, otherwise, don’t.You can add a span around your text and do the strikeout with css like this: