I'm looking to have the checkbox automatically checked when the <p> Tag is clicked in JavaScript

I need to modify the checkbox input so that when I click on any Todo Item, the checkbox is checked. However, after implementing the code below, it only works for the first element clicked. How can I make it work for each individual todo list item without clicking directly on the checkbox itself?

// Clicking Todo Item to fire checked Input 
 
let paragraphs =document.querySelectorAll('p');
let checkBoxInput = document.getElementById('checkedInput');
 

  for(var i=0; i < paragraphs.length; i++){
    paragraphs[i].addEventListener('click', function () {
          this.style.color = "#2a6850";
          checkBoxInput.checked = true;
      }, false);
  }

https://i.sstatic.net/UO7hd.png

How can I achieve the desired functionality as shown in the image, where clicking on a todo list item checks the corresponding checkbox and applies a line-through style to the text?

EJS File:

<div class="item">
    <input type="checkbox" name="" id="checkedInput">
    <p>
        <%= newItem %>
    </p>
</div>
CSS

input:checked + p {
    text-decoration: line-through;
    text-decoration-color: #2da883;
}

Answer №1

Consider using the label tag instead of p, allowing the browser to handle it for you.

This is an example of how your EJS file could be structured:

<div class="item">
    <input type="checkbox" name="checkedInput" id="checkedInput">
    <label for="checkedInput">
        <%= newItem %>
    </label>
</div>

Remember to ensure that each checkbox has a unique id after the app is rendered.

Answer №2

I successfully tackled the issue with my own code creation. Much gratitude to everyone who helped me out :)

let paragraphs = document.querySelectorAll('p'); 
let checkBoxInput = document.querySelectorAll('input[type=checkbox]');
        
for (var i = 0; i < paragraphs.length; i++) {
    paragraphs[i].addEventListener('click', function () {
        this.style.color = "rgb(228 233 253)";
        this.style.borderRadius = "10%";
        this.style.backgroundColor = "#0c0b07";
        this.previousElementSibling.checked = true;
    }, false);
}

https://i.sstatic.net/4LhgH.png

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

Utilizing imported components to set state in React

In my project, I created a functional component named Age and imported it into another functional component called Signup. This was done in order to dynamically display different divs on a single page based on the authentication status of the user. By sett ...

Having trouble with my delete button functionality in REACT

Whenever I attempt to delete using the button, nothing happens. Does anyone have any idea what might be causing this issue? My database is functioning correctly! Each time I click, I get a 404 error! I'm also seeing this warning: index.js:1 Warning: ...

How to Transfer Data from SuperAgent Library Outside the .then() Block?

I have a dilemma in my Nodejs project with two interdependent files. The key to this issue lies in the usage of a crucial library known as SuperAgent (I need it) Check out SuperAgent Library Here In file1.js const file2 = require('./file2'); ...

The outcome of the mongoose .exists function in JavaScript is a boolean value

Currently, I am delving into the world of node.js and mongoDB. For a project I'm working on, I've set up a demonstration login system to practice my skills. In my main API, I have a function that checks whether a refreshToken exists in the mongo ...

Confirming Identity using Fetch

In my React application, I am utilizing Javascript to interact with a database table called "users" which contains a boolean field indicating the user type (such as patient, doctor, etc). My goal is to check if a user exists and is not classified as a "pat ...

Tips for bundling Node.js server-side JavaScript

When building a server-side app using Express with Webpack, debugging can be challenging without the immediate comfort of a web browser. Debugging in tools like VS Code may not work smoothly due to breakpoints issues within request handlers when using sour ...

What causes flex box to behave differently when transitioning from two columns to three compared to shifting from three columns to four?

I am currently developing an application that presents a variable number of cards to the user in a grid format. The divs defining these cards have both maximum and minimum widths set (375px and 250px, respectively) and are enclosed within a flex container. ...

Node.JS Express implementation of Auth0 user management

I'm in desperate need of a solution to manage user data - including deleting, blocking, and editing users. Despite searching extensively, I have been unable to find a way to accomplish this task. Even the "auth0-openid-connect" module has not provided ...

Upgrade the arrow accordion in bootstrap by incorporating images instead

I have implemented a Bootstrap accordion with a toggle arrow. Here is an example: http://jsfiddle.net/zessx/r6eaw/12/ My question is, if I want to change the arrow with an image, what do I need to edit? Or how can I implement it? This is the image I want ...

Unraveling the mystery of the lingering NodeJS process: A guide to

I am facing a situation where my NodeJS process is not exiting even though all asynchronous operations should be completed. Is there a way for me to determine what is causing it to continue running? Can I view the heap stack of the running process somehow? ...

Different scenarios call for different techniques when it comes to matching text between special characters

I encounter different scenarios where strings are involved. The goal is to extract the text in between the || symbols. If there is only one ||, then the first part should be taken. For example: Useless information|| basic information|| advanced informa ...

Tips for refreshing the Vuex store to accommodate a new message within a messageSet

I've been working on integrating vue-socket.io into a chat application. I managed to set up the socket for creating rooms, but now I'm facing the challenge of displaying messages between chats and updating the Vuex store to show messages as I swi ...

Customizing background styles in real-time in a Meteor-Angular application

I'm currently working on a unique AngularJS Ionic Meteor application, and I am in search of a method to dynamically change the background color of the bottom box within an ionic card based on specific float values. The criteria for color changes are a ...

Updating a nested object within an array in a ReactJs component

I am struggling with updating a nested object within an array in the state of my React application. My goal is to determine if an item already exists in the state based on its name. Here's what I'm aiming for: Add an item to the cart. If th ...

How to include extra array in serialized form data using jQuery.ajax and retrieve it in PHP?

I am currently searching for an effective method to add extra data, especially an array, to serialized information from a form and be able to retrieve it using PHP later on. Despite numerous attempts, I have not been successful in finding a suitable soluti ...

Adding LocalStorage functionality to buttons in order to switch colors can be done by storing the

I've run into an issue trying to incorporate LocalStorage with the buttons that change colors as themes in JavaScript. I'm new to coding and eager to add this feature to my personal blog. $(document).ready(function () { $(".header--theme-button ...

"Applying CSS styles to expand the size of

Is there a way to prevent the blue div from overflowing the red div, but still always fill its parent container? I searched on stackoverflow and found suggestions to use height: 100%, but this causes issues when the child element has padding. How can this ...

How can I emphasize only a portion of a word in ReactJS and Material UI?

I am attempting to replicate this design: https://i.stack.imgur.com/H8gKF.png So far, this is what I have been able to achieve: https://i.stack.imgur.com/TJXXb.png My project utilizes Material UI and ReactJS. Below is a snippet of the code: bodyTitle: { ...

Convert alias query strings into parameters

I am currently working on a project that involves using node, express, and jade. I need to be able to access content through two different URLs: /Page/foo/bar and /Page?Foo=foo&Bar=bar The goal is for the top URL to act as an alias for the bottom o ...

When attempting to upload a photo using Multer and Cloudinary, I encountered an issue where req.file

Currently, I am in the process of creating an API for posting animal data which includes fields like name, type, etc. One of the fields is for uploading a photo, and for this, I am utilizing multer and cloudinary. However, I encountered an error stating "C ...