Tips for fading the text of list items when their checkbox is marked as done?

I am trying to figure out how to gray out a list item when its checkbox is checked. The code I currently have takes text input from a textbox and adds it to an unordered list when the add button is clicked. Each list item contains a checkbox within it. My goal is to have the list item become grayed out with a strike-through effect when its checkbox is checked. It's important to note that I'm not able to use jQuery or other JavaScript libraries for this solution. Here is my current code snippet:

    <head>
        <meta charset ="UTF-8">
        <meta name="description" content="Website">
        <title>Note Manager</title>
        <script>
            function createNote (form) {
                //Get the note text from the input box
                var noteText = form.inputbox.value;
                
                //Create the note element and append the text
                var note = document.createElement("li");
                note.innerHTML = noteText

                //Create a checkbox element
                var noteCheck = document.createElement("input")
                noteCheck.type = "checkbox"
                noteCheck.classList.add("checkcheck")

                //Append the checkbox to the note element
                note.appendChild(noteCheck)

                //Get the unordered list and append the note element to it
                document.getElementById("abc").appendChild(note)

            }
            function grayCheckedItems(){
                //Get the unordered list
                var list = document.getElementById("abc");

                //Get all list items from the unordered list
                var listItems = list.getElementsByTagName("li");

                //Iterate through the list items and gray out the ones with checked checkboxes
                for(var i = 0; i < listItems.length; i++){
                    var checkbox = listItems[i].getElementsByTagName("input")
                    if(checkbox.checked == true){
                        listItems[i].classList.add("completedItem")
                    }
                }
            }
        </script>
        <style>
            .completedItem{
                color: gray;
                text-decoration: line-through;
            }
        </style>
    </head>
    <body>
        <form name="myform">
            Enter a note: <br/>
            <input type="text" name="inputbox">
            <input type="button" name="button" Value="Add" onClick="createNote(this.form)">
        </form>
        <main>
            <h2>Task List: </h2>
            <ul id="abc" onchange="grayCheckedItems(this.ul)">

            </ul>
        </main>
    </body>

I need assistance in getting the list items to be grayed out when their associated checkboxes are checked. The current implementation is not achieving this intended behavior. Online resources have not provided solutions tailored to list items created dynamically using JavaScript.

Answer №1

A new functionality has been integrated into your checkbox creation process, where an onclick event handler toggles the .completeItem class on and off. Take a look at the updated code below.

function createNote(form) {
  //Retrieves the note text from the input box
  var noteText = form.inputbox.value;

  //Creates a new note element and adds the text to it
  var note = document.createElement("li");
  note.innerHTML = noteText

  //Generates a checkbox
  var noteCheck = document.createElement("input")
  noteCheck.type = "checkbox"
  noteCheck.classList.add("checkcheck")
  noteCheck.onclick = function() {
    if (this.checked == true) {
      this.parentNode.classList.add("completedItem");
    } else {
      this.parentNode.classList.remove("completedItem");
    }
  }

  //Appends the checkbox to the note
  note.appendChild(noteCheck)

  //Locates the unordered list and adds the note to it
  document.getElementById("abc").appendChild(note)

}

function grayCheckedItems() {
  //Accesses the unordered list
  var list = document.getElementById("abc");

  //Gets all list items within the unordered list
  var listItems = list.getElementsByTagName("li");

  //Correction needed: Iterate through each list item and apply a visual change to checked items
  for (var i = 0; i < listItems.length; i++) {
    var chekbox = listItems[i].getElementsByTagName("input")
    //console.log(chekbox)
  }
}
.completedItem {
  color: gray;
  text-decoration: line-through;
}
<form name="myform">
  Enter a note: <br/>
  <input type="text" name="inputbox">
  <input type="button" name="button" Value="Add" onClick="createNote(this.form)">
</form>
<main>
  <h2>Task List: </h2>
  <ul id="abc" onchange="grayCheckedItems(this.ul)">

  </ul>
</main>

Answer №2

modify the HTML output within an li element to display as follows:

<input type="checkbox"/><label>Test</label>

also, apply the following CSS style:

input[type=checkbox]:checked + label {
color: gray;  
}

Answer №3

Avoid using inline JS as it can clutter your HTML and come with its own set of drawbacks. Here is a more concise solution:

document.querySelector("#abc").onchange = function(e) {
  let textElement = e.target.previousElementSibling;
  e.target.checked ? textElement.classList.add("done") :
  textElement.classList.remove("done");
};

document.querySelector("input[name='button']").onclick = function() {
  document.querySelector("#abc").innerHTML += `
    <li><span>${this.previousElementSibling.value}</span> <input type="checkbox"></li>
  `;
}
span.done {
  color: gray;
  text-decoration: line-through;
}
<form name="myform">
  Enter a note: <br/>
  <input type="text" name="inputbox">
  <input type="button" name="button" Value="Add">
</form>
<main>
  <h2>Task List: </h2>
  <ul id="abc">

  </ul>
</main>

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

Troubleshooting issues with executeScript in Internet Explorer driver for Selenium

Unable to execute any JavaScript using "executescript" during functional tests in IE, while it works perfectly with Firefox. Despite hours of searching on Google, I haven't been able to find a solution. Here is an example of how I am trying to call i ...

Can a jQuery/JavaScript script be run standalone?

I've got a bunch of HTML pages saved on my computer and I'm looking to create a JavaScript script that can extract specific text or elements from those pages. I found some jQuery code snippets on Stack Overflow that do what I need, but I'm n ...

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

Error encountered: Unexpected identifier in Reactjs code

I created a new application using create-react-app and encountered an Uncaught SyntaxError: Unexpected identifier for this particular line: import React, { Component } from 'react'; within the file public/scripts/app.js: 'use strict' ...

NodeJS is facing a severe challenge in properly rendering HTML and its accompanying CSS code, causing a major

Once upon a time, I built a beautiful website while practicing HTML, CSS, and JS. It had multiple web pages and used Express for the backend. Unfortunately, I lost all the files associated with it and took a break from web programming for some time. Now, w ...

Designing GWT FlexTable using pure CSS styling

Is there a way to style a GWT FlexTable using CSS alone? The API doesn't provide information on available CSS classes. Are there no predefined classes and do I need to define them myself? I am particularly interested in styling the "th" element. ...

get the queryset for a dropdown menu item in Django

Currently, I am in the process of creating an HTML calendar page with a dropdown feature to select different months. Accessing this calendar page can be done through the navigation bar set up in my base.html base.html - Direct access to the calendar page. ...

What are the steps to ensure a successful deeplink integration on iOS with Ionic?

Recently, I was working on a hybrid mobile app for Android/iOS using Nuxt 3, TypeScript, and Ionic. The main purpose of the app is to serve as an online store. One important feature involves redirecting users to the epay Halyk website during the payment pr ...

Tips on incorporating the vue package

I recently started using Vue and decided to incorporate a plugin called vue-toastr. I'm attempting to integrate it with Laravel, which already has Vue set up with the plugin. Unfortunately, I keep encountering an error that says "TypeError: Cannot rea ...

Tips on aligning border-radius with parent border-radius

Seeking to create a text box with a sleek line on the left side for design flair. The challenge arises when attempting to match the thickness of the line with the border radius of 10px. After various unsuccessful attempts, here is the current solution: ...

Bookmarklet in JavaScript that automatically extracts and displays Meta keywords in a new tab within the browser

I successfully implemented a script that extracts site meta keywords and writes them into the DOM. javascript:(function metaKeywords() { metaCollection = document.getElementsByTagName('meta'); for (i=0;i<metaCollection.length;i++) { nameAttri ...

Achieve a div to fill the remaining width while using list-style-position: inside

I have been attempting to make another div occupy the remaining space in the numerical list item using list-style-position: inside, but it does not seem to be working for me. While I could opt for list-style-position: outside and add some spacing to avoid ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...

Is the input in the array? How to find out?

I am currently facing an issue with a script that I have created to count array elements matching a user input. Strangely, all if statements in the script seem to be returning false. I have verified that both the array element and the input value are stri ...

Encountering a 401 Error while trying to host an Angular app on Google Cloud Storage

I am currently facing an issue with deploying my Angular app to a Google Cloud Storage bucket. The bucket is public and set up to be served as a custom website via CNAME (test.example.com). The main page and 404 handler are mapped to index.html, but I am e ...

I need help setting up a link in HTML that redirects to the correct webpage when clicked. How can I make this happen smoothly?

<!DOCTYPE html> <html> <head> <title>______</title> <button class="btn about">About</button> <button class="btn socialmedia">Social Media</button></button> <button class ...

(Original) redirect from specific url / url detection New text: "Redirection

Sorry for the long and confusing question, my apologies for wasting your time. I am still learning programming and what I really wanted to ask is "how can I retrieve a GET parameter using JavaScript?" Apologies for any inconvenience. ...

Issues with ellipses not functioning properly have been identified specifically on Safari when using the line

Currently, I am using the line-clamp feature to restrict the titles on a blog to only two lines at most. This functionality works perfectly fine on Firefox and Chrome browsers; however, when it comes to Safari, the ellipsis appears in the middle of the sen ...

Experience the classic game of rock-paper-scissors brought to life through JavaScript and HTML,

I've been working on a rock, paper, scissors game in JavaScript and I'm struggling to get the wins and losses to register correctly. The game keeps resulting in a draw even though I've checked my code multiple times. It's frustrating be ...

CSS - borders are overlapping with one another

Encountering an issue where the bottom border is overlapping the right border on the same element. Here's a visual representation of the problem: The green right border's bottom is appearing distorted due to the presence of the gray border at t ...