How can I make my div change color when the check-box is selected?

I have a dynamic table in my web application that is populated with data from a database. Each row in the table represents multiple time slots for a specific date. I am working on a feature where the background color of a time block can be changed if a checkbox next to it is checked. While I successfully implemented the functionality of the checkbox, I faced challenges when trying to change the background color dynamically based on its status. Here is an excerpt of my code:

 <cfoutput query="qryTest" group="DateMeeting">
         <tbody>
            <tr>
                <td>#DateMeeting#</td>
            </tr>
            <cfoutput>
               <tr class="blockRow">
                  <td>#StartTime#</td>
                  <td>#EndTime#</td>
                  <td><input type="checkbox" name="block" id="block"></td>
               </tr>
            </cfoutput>
         </tbody>
 </cfoutput>

JavaScript:

$('input[type=checkbox]').on('change', function() {
    var div = $(this).closest('.blockRow');
    $(this).is(":checked") ? div.addClass("highlight") : div.removeClass("highlight");
});

CSS:

.highlight{
   background-color: lightblue; 
}

This solution now works seamlessly after making adjustments to the structure of the HTML and utilizing jQuery for better control over elements. With the help of the community, I was able to overcome initial issues and create a user-friendly experience for modifying the appearance of time blocks. Thank you all for your input!

Answer №1

Check out this solution:

$('input[type=checkbox]').on('change', function() {
    var div = $(this).closest('.blockRow');
    $(this).is(":checked") ? div.addClass("red") : div.removeClass("red");
});

.red{
    background-color:red; 
}

<cfoutput query="qryTest" group="DateMeeting">
    <tbody>
        <tr>
            <td>#DateMeeting#</td>
            <cfoutput>
                     <div class="blockRow">
                     <td>#StartTime#</td>
                     <td>#EndTime#</td>
                     <td><input type="checkbox" name="block" id="block"></td>
                 </div>
            </cfoutput>
        </tr>
    </tbody>
</cfoutput>

View the code on jsfiddle:

https://jsfiddle.net/3s83gj70/2/

This code identifies the closest blockrow to the current checkbox, making it adaptable for multiple instances. It uses classes instead of IDs to avoid conflicts.

If you need to perform different actions based on the checkbox status, you can modify the code like this:

$('input[type=checkbox]').on('change', function() {
    var div = $(this).closest('.blockRow');
    if($(this).is(":checked")){
        div.addClass("red");
        // Perform action when checkbox is checked
    }
    else
    {
        div.removeClass("red");
        // Perform action when checkbox is unchecked
    }
});

Answer №2

Simple:

 $('#blockRow').css("background-color","red")
 ------------------------------^

UPDATE

If you prefer not to use jQuery library, you can achieve the same result with pure JavaScript like this:

http://jsfiddle.net/bfss81sa/

 document.getElementById("box").style.backgroundColor = "red";

Below is the complete code snippet:

  var cbs = document.querySelectorAll('input[type=checkbox]');
  for(var i = 0; i < cbs.length; i++) {
    cbs[i].addEventListener('change', function() {
      if(this.checked) {
        document.getElementById("box").style.backgroundColor = "red";
      } else {
        document.getElementById("box").style.backgroundColor = "transparent";
      }
    });
  }
<input type="checkbox" name="block" id="block">
<div id="box">
The box
</div>

Answer №3

Your HTML code could use some tidying up. Here is a suggestion:

$('input[type=checkbox]').click(function() {
  if($(this).is(':checked') {
    $(this).parents('tr').find('td:first').css('background', 'red'); 
  } else {
    $(this).parents('tr').find('td:first').css('background', 'white');
 }
});

You can also specify the scope of the input checkbox selector for better performance. If the <td> is not the first one in your <tr>, consider assigning it a specific class.

Remember, the structure of your DOM is important. Incorrect nesting like <cfoutput> within <tr> or having <td> as a direct child of <div> can impact JavaScript traversal.

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 could be causing my bounce animation to begin 50 pixels higher than its intended starting point?

Trying to create a bouncing effect on text Check out my attempt here. It seems like the bug is in this area. @keyframes bounce{ 0%, 40%{ transform:scale(2,.5) translate(0,100px); } 45%,55%{ transform:translate(0,-50px); } 55%, 100%{ ...

modify the color of a box within a grid upon clicking it

I am curious if it is possible to change the color of a box when it is clicked. I am working on coding a "calculator layout" and would like to start with this part 1 2 3 4 5 6 7 8 9 0 This is what I have been working on and struggling with. $(docume ...

Tips for showcasing a complete background image in a div even if the content inside is minimal

Check out the header image on ink.talentosoft.com if you get a chance. The height of the header image is precisely 388 px. I am looking to have the background of this div fully displayed. Currently, the setup for the div looks like this: background: url ...

How to download and install Google Chrome Canary on your Android or iPhone device

I've been diving into a HTML 5 Web Audio Input project lately. I'm keen to test it out on my Android/iPhone devices, but after some research, I discovered that it only functions properly in Google Chrome Canary. The problem is, I can't seem ...

Why won't hover over function properly in separate divs for two items?

My goal is to show text when hovering over a logo, but the text and logo are in different divs. Despite trying various solutions like using display: none and display: block, I still can't get it to work. import styles from '../styles/Float.module ...

Ways to decrease the space between lines of text within a single mat-option element

::ng-deep .mat-select-panel mat-option.mat-option { height: unset; } ::ng-deep .mat-option-text.mat-option-text { white-space: normal; } Currently, I have implemented this code to ensure that text in options wraps to the next line when it's too ...

Input field with a calendar option? Validating dates using jQuery

Getting straight to the point. I have a form with multiple controls and I am implementing validations. I am having trouble with attaching a DATE-PICKER to one of my text boxes and validating it accordingly. Instead of allowing users to enter anything in ...

Screening through the outgoing html documents

For all my *.html files, I have added custom syntax that must be filtered through filter.php before being displayed. I believe this can be achieved using .htaccess. It's important to note that I do not want the *.html files to be parsed as PHP. ...

Position a Bootstrap 3 division within a central division for ultimate centering

I have written a code snippet that looks like this- html, body, .container-table { height: calc(100% - 50px); } /*Centering a div*/ .container-table { display: table; } .vertical-center-row { display: table-cell; vertical-align: middle; } < ...

Socket.io-powered notification system

I'm currently in the process of developing a notification system for my Events Manager Website. Every time a user is logged in and performs an action (such as creating an event), a notification about the event creation should be sent to other user ...

Steps for opening a clicked link in a new tab:

I have a link on my page that I would like to open in a new tab when clicked, but it doesn't seem to be working. Can anyone offer some suggestions or help? So far, I've tried the following code: <a target="_BLANK" ng-href="{{news.url ...

There was an error due to a TypeError: The 'page' property cannot be read because it is undefined

Can anyone assist me with an Angular issue I'm facing? I've been working on integrating server-side pagination, but no matter how many times I revise my code, I keep encountering the same error message: ERROR TypeError: Cannot read properties o ...

Failure to retrieve blob - net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK)

My fetch request code in my front end for a node js express web app hosted on MS Azure works well for small zip file blobs. However, it times out and displays the error net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK) when dealing with large blobs. ...

instructions on how to eliminate slideUp using jquery

I am trying to eliminate the slide-up function from my code $( document ).ready(function() { $("#tabBar ul.buttons > li > a").on("click", function(e){ //if submenu is hidden, does not have active class if(!$(this).hasClass("activ ...

There is no POST data present in the jquery ajax request

I have been attempting to send data back to a controller using ajax from a lightbox, but unfortunately, it is not working as expected. The issue arises when I select values from two populated select lists and click submit – an error message briefly appe ...

Submitting Data Forms with AJAX on dynamically loaded webpages

Issue with Form Submission in Ajax-Generated Page I am experiencing an issue with form submission on a page generated within AJAX. The page contains two forms, #form1 and #form2. The jQuery code for submitting the form is as shown below: jQuery("#form1" ...

What is the best way to add a key to a JavaScript array while keeping it reactive in Vue.js?

If there's an array in the state: state: { users: [] }, Containing objects like: { id: 1, name: "some cool name" } To add them to the store using a mutator like users.push(user);, how can we ensure that instead of 0:{...}, it uses the ...

The function is limited to a single use

Whenever I click on the blue color, my function works just fine. However, once I try to change it back to black, it stops working altogether. What could be causing this issue? Is there a simpler way to achieve the desired functionality? I have confidence ...

Animating the smooth collapse of panels within listviews

I have successfully implemented a smooth animation code for a collapsible panel, and it is working wonderfully: <script type="text/javascript"> function pageLoad(sender, args) { smoothAnimation(); } function smoothAnimation() ...

I am experiencing issues with a few of my design choices not functioning correctly

I am facing issues with some of my styles. I have put in a lot of effort, but there seems to be a problem with my menu. The last part of my CSS is not functioning correctly. When hovering over the menu content, I want it to turn black and... #site_menu { ...