Events triggered when a Jquery checkbox is toggled between checked and unchecked

I have written some HTML code that utilizes jQuery to manage checkboxes.

<tr>
    <td>
      <div class="checkbox">
        <label><input type="checkbox" id="checkbox2"></label>
      </div>
    </td>

    <td><p id="taks2">Task 2</p></td>

    <td><span class="glyphicon glyphicon-trash"></span></td>        
  </tr>

Here is the jQuery script:

<script>
    $(document).ready(function(){
        $('#checkbox2').click(function(){
            if($(this).is(":checked")){

                $('#taks2').replaceWith('<s>' + $('#task2').text() + '</s>');


            }
            else if($(this).is(":not(:checked)")){

            }
        });
    });
</script>

If a user checks the checkbox, "Task 2" will be strikethrough text (output using del or strike tag). If the checkbox is unchecked, it will revert back to "Task 2".

Answer №1

To modify the styling of a text when a checkbox is checked or unchecked, you can utilize a CSS class and jQuery:

$(document).ready(function(){
  $('#checkbox2').click(function(){
      if($(this).is(":checked")){
        $('#taks2').addClass('strike');
      } else {
        $('#taks2').removeClass('strike');
      }
  });
});
.strike{
  text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <div class="checkbox">
      <label><input type="checkbox" id="checkbox2"></label>
    </div>
  </td>

  <td><p id="taks2">Task 2</p></td>

  <td><span class="glyphicon glyphicon-trash"></span></td>        
</tr>

An alternative approach is to streamline your code using toggleClass() as shown below:

$(document).ready(function(){
  $('#checkbox2').click(function(){
      var isChecked = $(this).is(":checked");
      $('#taks2').toggleClass('strike', isChecked);
  });
});
.strike{
  text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <div class="checkbox">
      <label><input type="checkbox" id="checkbox2"></label>
    </div>
  </td>

  <td><p id="taks2">Task 2</p></td>

  <td><span class="glyphicon glyphicon-trash"></span></td>        
</tr>

Answer №2

To achieve this effect, you can utilize only CSS by targeting the next label of a selected checkbox:

input[type='checkbox']:checked + label {
  text-decoration: line-through;
}
<div class="checkbox">
   <input type="checkbox" id="checkbox1" /><label>Task 1</label>
</div>
<div class="checkbox">
   <input type="checkbox" id="checkbox2" /><label>Task 2</label>
</div>

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

Div flexes and compresses smaller than its content dimensions

Here's a link to the fiddle: check it out Take a look at a normal card below: https://i.sstatic.net/7Yqqv.png But when the browser window is resized, it shrinks to this: https://i.sstatic.net/1aexK.png This is the HTML structure: #product-list ...

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

Trouble with Jquery Library Clash: Overlay Feature Malfunctioning

Having a JQuery conflict is causing two functionalities on my website to not work together. I've attempted to rearrange the script order and change the $ function to the jQuery function, but it doesn't seem to resolve the issue! <div id="ma ...

Steps for adding a Bootstrap Navbar Dropdown1. Begin by creating

Looking for tips on how to incorporate a dropdown navbar using Bootstrap 4. I've utilized the .navbar-bottom class to achieve a horizontal layout.** The .navbar-bottom class is used to include a scrollbar in the navbar** .navbar-bottom { overflow ...

Exploring the functionality of the onblur HTML attribute in conjunction with JavaScript's ability to trigger a

How do the HTML attribute onblur and jQuery event .trigger("blur") interact? Will both events be executed, with JavaScript this.trigger("blur") triggering first before the HTML attribute onblur, or will only one event fire? I am using ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

navigation menu 'selective emphasis' feature

I have created a JQuery script that will highlight the 'About', 'My Projects', or 'Contact Me' text on the navigation bar when the corresponding section of the page is in view. To achieve this, I am using a scroll() event list ...

Managing Session Cookies in ExpressJS

Hey there! I've been dealing with a problem while using Express-Session to manage my server-side sessions. When I set user data to session variables in one file, it works perfectly. However, when I try to access those variables in another file, all I ...

What is the best way to toggle the visibility of my menu using JavaScript?

I recently implemented a script to modify a CSS property in my nav bar as I scroll down, triggering the change after reaching 100px. $(window).scroll(function() { var scroll = $(window).scrollTop(); //console.log(scroll); if ...

Choose a child of a parent by specifying the index

:nth-child() - serves as a selector that targets every element which is the nth child of its parent. Is there a method to select a specific child of a parent using an index value? I need to access and modify each child's attributes separately. The o ...

Tablesorter's filter_selectSource function filters out options that are not relevant to the current page when using server-side pagination, and organizes the select options

Working with Python/Django, I am configuring arrays for Tablesorter's filter_selectSource. Initially, I encountered some strange behavior when switching to server-side filtering. The dropdown options would only appear when a single symbol was typed in ...

Modify the attributes of a CSS class according to the chosen theme (selected within the user interface) in Angular 8

I have a custom-built application with Angular 8 where users can switch between two unique themes in the user interface. I have a specific div class that I want to change the background-color for each theme, but unfortunately I am having difficulty achievi ...

Is it true that undefined >>> 0 equals 4294967295?

Is it normal to receive different results on various machines when using the '>>>' operation, or could there be an error in the implementation for specific CPUs? Linux qemux86-64 4.18.41-yocto-standard #1 SMP PREEMPT Tue Oct 8 20:33:31 ...

Obtaining a fresh access token from a refresh token using the googleapis npm library

I've been searching everywhere for an explanation, but I can't seem to find one. The documentation I've read says that refresh tokens are used to obtain new access tokens, but it doesn't explain the mechanics behind it. Normally, I wou ...

The error message "Uncaught TypeError: Cannot read property '0' of undefined" is triggered when using toDataURL

Recently diving into the world of JavaScript and facing a perplexing error. I must be overlooking some fundamental concept... apologies in advance. Here is the issue at hand. In my HTML file, this snippet of code is present: <div> <script type= ...

Storing email addresses in variables and sending them using node.js

const functions = require('firebase-functions'); var nodemailer = require('nodemailer'); var transporter=nodemailer.createTransport('smtps://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dca9afb9aeb2b ...

The attempt to change the header's background color has proven to be unsuccessful

Hello this is my first question on stackoverflow so please forgive my lack of experience. I am attempting to modify the background color of an entire HTML document using the background-color property on the element. Despite changing some parts of the docu ...

Using CSS, create a layout with a small 2x2 box positioned beside a larger 2x2 box

https://i.sstatic.net/nC2PI.png Can a flexible ul li structure be achieved with flexbox? I attempted to set the width of the squares to 25% and make the 1st, 3rd, or 5th one 50% wide using a combination of float:left, clear[left|right], but the last squar ...

Why aren't variables showing up on the right when using writeFileSync in Node.js?

I'm attempting to insert a variable as ${Y} but instead of getting the actual data in Y, my output is showing (how can I write variable ${Y}). Does anyone have a solution for this? const fs = require('fs'); const Y = fs.readFileSync('./ ...

Having trouble converting a name to binary? Clicking on JS isn't producing any results? Don't worry,

Just starting out as an absolute beginner with programming and watching some tutorial videos. I've got VSC installed, but it's not displaying any errors when I run it. Any suggestions for a better program than VSC? I'm trying to convert Inp ...