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

Problem with exporting default class in Babel/Jest conflict

Currently, I am facing a challenge while testing the code using jest. The issue seems to be related to babel, especially regarding the export of a default class. Here is an example of the code causing the problem... export default class Test { get() { ...

Tips on adding background images to your chart's background

Is there a way to set an image as the background in Lightning Chart using chartXY.setChartBackground? ...

Angular ng-if directive contains a specific class

I am trying to create a directive that will only be active when an element has a specific class. I have tried the following code: <feedback-analytics ng-if="$('#analyticTab').hasClass('active')"></feedback-analytics> Unfor ...

Ways to speed up the initial loading time in Angular 7 while utilizing custom font files

Storing the local font file in the assets/fonts folder, I have utilized 3 different types of fonts (lato, raleway, glyphicons-regular). https://i.stack.imgur.com/1jsJq.png Within my index.html under the "head" tag, I have included the following: <lin ...

Organize group data by month in a visually appealing table using HTML/PHP with

I have successfully implemented a code that prints HTML table rows from a database table and sorts them by date. The challenge lies in the fact that the date is stored as VARCHAR (due to a pre-existing project with an active database used in a PHP web app ...

Exploring the Differences Between Meteor JS Backend and Express JS

I have a basic understanding, but I'm interested in learning more: I came across a comparison on Stack Overflow that likened Meteor JS and Express JS to oranges and potatoes. My current understanding is that Meteor JS is full stack (Front End, Back E ...

The functionality does not seem to be functioning in Mozilla Firefox, however it is working correctly in Chrome when the following code is executed: `$('input[data-type="choise"

I am currently working on an online test portal and everything is functioning properly with Chrome. However, I am encountering an issue with Mozilla Firefox. My code works fine in Chrome but not in Mozilla Firefox. Please suggest an alternative solution to ...

Create an array in JSON format that includes a JavaScript variable, with the variable's value changing each time a mouse

var question="What is your favorite color?"; var option="red"; var col=[]; When the user clicks, the variable value changes and values should be pushed in a specific format. I am new to JavaScript, please help me with this. Thank you. //On click, the var ...

Adjust the text orientation using CSS within an SVG element

Here is the SVG code snippet that I am working with: https://jsfiddle.net/danpan/m3ofzrc1/. It generates the image shown below. The image consists of two lines of text wrapped around a circle: HELLO_WORLD_1 HELLO_WORLD_2 I want to change the direction ...

Can you explain which variable is considered global in Node.js?

Instead of writing var global = window for the browser I want my code to be able to work in a node environment as well. Something like var global = window || node_global What is node_global? I couldn't find any clear answer here: or here https ...

How can I access an InputStream from a local XML file in a PhoneGap application?

Looking for advice on how to fetch an inputstream from a local XML file using JavaScript in my PhoneGap application. I'm new to JavaScript, so any guidance would be appreciated! ...

How to efficiently send multiple objects in response to a single GET request with Express and Node.js

The code snippet I am working with looks like this - sendServer.get('/download',function(request,response){ var status="SELECT * from poetserver.download where status='0'"; console.log(status) connection.query(status,function(error,ro ...

What causes TypeScript's ReadonlyArrays to become mutable once they are transpiled to JavaScript?

Currently, I am in the process of learning Typescript by referring to the resources provided in the official documentation. Specifically, while going through the Interfaces section, I came across the following statement: TypeScript includes a special t ...

Tips on using the Hover property in CSS for an element that includes both :after and :before properties

I've created a hexagon using CSS after and before properties, and now I'm attempting to add a glowing effect around the hexagon when hovering. It works perfectly for the center of the hexagon but not for the top and bottom points of the shape. ...

What is the best way to hide a custom contextmenu in AngularJs?

I created a custom contextmenu directive using AngularJs. However, I am facing an issue where the menu is supposed to close when I click anywhere on the page except for the custom menu itself. Although I have added a click function to the document to achie ...

The output from the Python and SQLite combination is accurate, however the HTML rendering is not displaying the data correctly

Retrieving data from a database using different methods can yield varied results. When the method is set to 'get', it returns all information, but when it's 'post', it only returns the searched item. Although the post method return ...

Adjusting the size and positioning of an image with CSS

Here is my situation: I am working with an image that is 1900 x 1600 pixels in size. I also have a div that is sized at 200 x 150 pixels. To adjust the image size, I used the following CSS: max-width:300px; max-height:300px; The height will be adjuste ...

What is the simplest method for fetching and parsing JSON data with jQuery and JavaScript?

I'm having trouble making this code snippet work. I can't seem to figure it out. The objective is to retrieve and parse a JSON object in the simplest and easiest way possible. Here's the code snippet. <!DOCTYPE html> <html> &l ...

There seems to be an issue as req.files in Sails.js is blank and the value of req

I've been struggling with this problem for quite some time now. Despite my efforts to find a solution through Google and StackOverFlow, I have not been successful. The issue lies within a project I am working on, where I have implemented a "Product" M ...

Is bower install failing to detect a local npm package?

After running bower install, I encountered the following error message: $ bower install module.js:340 throw err; ^ Error: Cannot find module 'minimist' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._l ...