If the box is ticked, the class will be added; if not,

Unable to implement a feature in my Laravel project where the title's text should have 'line-through' style when a checkbox is checked, and normal otherwise. The jQuery function I attempted doesn't seem to work. Can anyone help me with this issue? Below is the code snippet from my blade file:

<tbody>
    @forelse($tasks as $task)
    <tr>
        <td>
            <div class="icheck-primary d-inline ml-2">
                <form
                        style="display:none"
                        id="form-checked-{{$task->id}}"
                        action="{{ route('completed.update',$task->id) }}"
                        method="post">
                    @csrf
                    @method('put')
                </form>
                <input
                type="checkbox"
                class="icheck-primary d-inline ml-2"
                id="linethrough"
                onclick="event.preventDefault();
                if(confirm('Want\'s to complete the Task!')){
                    $('#form-checked-{{$task->id}}').submit();
                }
                "
                {{ !empty($task->completed_at) ? 'checked' : '' }}/>
            </div>
        </td>

        <td class="myjqueryclass" id="clls-{{$task->id}}">
            {{$task->title}}<br>
        </td>
    </tr>
    </tbody

The issue lies within my jQuery function:

<script>
    $(document).ready(function($id){
        $('input[type="checkbox"]').click(function(){
            if($(this).is(":checked")){
                $('#clls-' + $id).addClass('addlinethrough');
            }
            else if($(this).is(":not(:checked)")){
                $('#clls-' + $id).removeClass('addlinethrough');
            }
        });
    });
</script>

Here's the CSS class used:

<style>
    .addlinethrough {
        text-decoration: line-through;
    }
</style>

If you have any alternative solutions or suggestions, please feel free to share. One observation is that the state isn't retained when using a class name instead of an ID.

Answer №1

For an easy way to add toggleClass, you can refer to the documentation at https://api.jquery.com/toggleclass/. Implementing it in your code would look like this:

$(document).ready(function($id){     
  $('input[type="checkbox"]').click(function(){
    $('#clls-' + $id).toggleClass('addlinethrough', $(this).is(":checked"));
  });
});

// Using vanilla javascript

const checkboxElement = document.getElementById("linethrough");
const elementWithLineThrough = document.getElementById("someId");

checkboxElement.addEventListener("click", () => {
  const checkboxStatus = checkboxElement.checked;

  // Add or remove class based on checkbox status
  elementWithLineThrough.classList.toggle("addlinethrough", checkboxStatus);
})

Answer №2

Please include a data-id attribute in the input checkbox tag.

 <input
    type="checkbox"
    class="icheck-primary d-inline ml-2"
    id="linethrough"
    data-id="{{$task->id}}"
    {{ !empty($task->completed_at) ? 'checked' : '' }}/>


<script>
    $(document).ready(function () {
        $('input[type="checkbox"]').click(function () {
            let id = $(this).data('id');
            $('#clls-' + id).toggleClass('addlinethrough', $(this).is(":checked"));
            if (confirm('Want\'s to complete the Task!')) {
                $('#form-checked-' + id).submit();
            }
        });
    });
</script>

This code has been tested with jquery-3.5.0 and it is functioning correctly.

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

What is the importance of using mb_convert_encoding in order to display the characters correctly?

My website and MySQL database are both set to use UTF-8 encoding. An issue I am encountering is that when retrieving text from the MySQL database to display on the website, I need to utilize the PHP function mb_convert_encoding(@db_field,'utf-8' ...

Struggling to refresh page due to several getJson requests

I have a HTML page where I am showcasing data from 3 different websites using WordPress API in 3 separate sections of the HTML. Below is my script code: <script> $(document).ready(function(){ $.getJSON("https://thebigscope.com/wp-jso ...

Unexpected behavior when using AutoComplete in Material UI

Currently, I am developing a small application using react-redux and material-ui. However, I have encountered an issue with the autocomplete field while implementing the onNewRequest property. Instead of triggering when I select an element from the list, i ...

Height specification in Tailwind Grid

Hi there! I'm currently working on implementing a grid system in NextJS using Tailwind CSS. However, I've hit a roadblock when it comes to automatically sizing the grids to fit the parent element. Let me illustrate my issue with two images below ...

Modifying the $scope property on ng-click and redirecting with ui-sref

I am completely baffled by this situation. Here is the current status: https://i.sstatic.net/PJdb6.png Upon reaching this page, the following appears in the console: https://i.sstatic.net/aIJqd.png When I click on "lorem2", which has an ng-click funct ...

"Any tips on maintaining the blue color of my dropdown link when it is selected as active

I'm struggling to keep the bootstrap accordion dropdown link blue when it's active. I've tried different methods but none seem to work. What am I missing? Here's my code: <div class="visible-sm visible-xs" id="accordion" role="t ...

What is the recommended image size for Next.js websites?

According to documentation: The width of the image, in pixels. Must be an integer without a unit. The height of the image, in pixels. Must be an integer without a unit. https://nextjs.org/docs/api-reference/next/image Different devices come in various ...

The challenge of managing race conditions in NodeJS with socket.io

Currently, I am facing caching issues with socket io where I need to update values quickly (20 simultaneous requests). However, when I make a get request to check the updated values, the response I receive is not accurate. For example, I expect a result of ...

Showing a numerical value in a modal text box with the combination of PHP and Jquery

How can I display values from an SQL Database onto a textbox using PHP and JQuery? The values are being retrieved but not displaying on the textbox. Can anyone help me troubleshoot this issue? <?php require 'UpdateTimerSQL.php'; ?> < ...

Activate the end trigger with Scrollmagic

I am new to using ScrollMagic and have been able to understand how to trigger my animation based on the starting element and duration Is there a way to set an end trigger instead of a duration? let smcontroller = new ScrollMagic.Controller(); let smscene ...

Enhance Your R Shiny Leaflet with JavaScript Addons for Stunning Heat

I am currently exploring the use of a javascript addon for leaflet called the heatmap functionality, which can be found at https://github.com/Leaflet/Leaflet.heat. My goal is to integrate this feature into Shiny, however, it seems that the leaflet package ...

How can a CoffeeScript project be converted to JavaScript without minification?

I am currently working with a specific jQuery plugin that is written in CoffeeScript. I am interested in converting the project into regular JavaScript code for better understanding. The structure of the library seems well-organized with good OOP practic ...

The Tailwind Typography plugin simply maintains the default font size of heading tags without altering their style

I've been working on parsing an MDX file and converting it into React components. My tech stack includes TailwindCSS, Next.js, and React. Following the Tailwind documentation, I have installed the tailwind/typography plugin. In my tailwind.config.js ...

Generate fake data for all possible combinations using JSON faker

In my current project, I am in need of creating test data for a JSON schema. I came across this fantastic github resource that has been incredibly helpful: https://www.npmjs.com/package/json-schema-faker#overview Now, how can we expand it to generate all ...

You cannot use jQuery to initiate a button click event through another button click event

I'm currently facing an issue where I want to replace one button with another, but it's not going as smoothly as I hoped. When I click the first button, everything works fine. However, when I click the second button, which is supposed to trigger ...

Troubles with HTML and div elements

I have a specific need to dynamically load HTML into a div container with the style attribute overflow set to hidden. I have implemented next and previous buttons for navigation, but I am facing an issue where the content overlaps at the beginning and end ...

Tips for dynamically creating column headings and table values using JSON arrays in AngularJS

On a web page, there are two radio buttons that produce different results: The first button shows Student Details and the corresponding JSON array is as follows : [{"Name":"A", "Class":"x", "Section":"abcd", "DOB": "XYZ"}, {"Name":"B", "Class":"x", "S ...

Rounding off numbers with decimal points

I am dealing with product prices and have the following numbers: <span class="amount">77.08</span> <span class="amount">18.18</span> <span class="amount">20.25</span> My goal is to always round them up, regardless of t ...

Encountering a Laravel Nova issue where attempting to override a Vue component leads to a Vue warning: Error

Recently, I decided to incorporate a user guide into my nova using the following Vue Shepherd library. To make this work, I made some adjustments in the files within the nova directory. One of these changes involved renaming the file "webpack.mix.js.dist" ...

Menu using JQuery and CSS does not overlap a fixed div on an iPad device

I've been working on a website with a fixed top div featuring a basic dropdown menu and a fixed left div below it. The issue I'm facing is that when viewing the site on an iPad, the submenu items appear under the fixed left div instead of where t ...