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 are some effective ways to test asynchronous functions in React?

Looking for help to test async/Promise based methods in React components. Here is a simple example of a React component with async methods: import server from './server'; class Button extends Component { async handleClick() { if (await ca ...

Slide up the bottom of the page using Jquery

Having trouble with the accordion feature on my website. I have a section where users can click to expand the content at the bottom of the page, but I have to manually scroll to see the expanded content. I've tried various solutions like using toggle ...

My goal is to retrieve and print the duplicated values only once from an associative array

Given an associative array, I need to print all the department names without any repetitions. <h3>2. List out all department names</h3> <div class="all"> </div> Here is my JavaScript code: var employee=[{"firstName":"Zahir","last ...

Upon introducing the CSS loader into the webpack configuration, TinyMCE unexpectedly ceases to function

My application development journey began with cloning code from https://github.com/DMPRoadmap/roadmap. This project is based on webpack and npm. To integrate select2, I executed npm install select 2 in the lib/assets directory. I aimed to incorporate a ...

Altering the width of an unordered list (<ul>) to fit menu items with the help of jQuery

I had previously asked a question that I need further assistance with: Fitting a <ul>'s width to accommodate the menu items Is there a way to use jQuery to adjust the width of each <ul> within a specific parent <ul> so that the <l ...

An array containing concatenated values should be transferred to the children of the corresponding value

Consider this example with an array: "items": [ { "value": "10", "label": "LIMEIRA", "children": [] }, { "value": "10-3", "label": "RECEBIMENTO", ...

Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway. https://i.stack.imgur.com/S5Zx9.png Both FastAPI and API Gateway have CORS enabled, b ...

What is the best way to prevent my form from saving empty values to the database?

I am currently working on a project for managing library resources using HTML5, PHP, and SQL. I have implemented form validation using PHP for fields such as email, password, name, surname, and phone number. The validation seems to work visually, but it st ...

Add HTML content individually to each item in the array

I am currently developing a plugin and I need to load a preset in order to populate a form with the relevant data. In an attempt to write concise code, I created a variable called "template" that looks like this: var Fields = '<div c ...

The process of exporting and utilizing models in Sequelize

When working on my node.js project with sequelize, I encountered a challenge of exporting and using table models in another file. I typically save table models in a folder, for instance Profile.js. module.exports = (sequelize, DataTypes) => sequelize.d ...

Get a collection of images packed into a single zip file

My current function downloads multiple images and saves them to a user's "download" folder, although it only works in Chrome. I am looking to enhance this function by combining the downloaded images into a single zip file. Below is my existing code. ...

What steps should I take to convert this from a string to HTML format?

I recently encountered an issue where my code was being converted into a string instead of the HTML output I intended to achieve. My main query is how can I convert this into innerHTML before it gets converted? Is there any way to accomplish this task if ...

Having trouble retrieving data through ajax with django

I'm having trouble showing sizes using AJAX, as they don't appear after the AJAX call is successful. Below is the AJAX script: <script type="text/javascript"> function getStoreView(event, productId) { event.preventDefault(); ...

CSS animations are only functional when the Developer Tools are activated

I recently implemented a transition to uppercase in CSS, but it seems to only work when I open dev tools in Mozilla and not at all in Chrome. This is my first attempt at using animations in CSS, so any feedback on my code is appreciated. I'm curious ...

Image input not working in Internet Explorer

While the button displays correctly in Chrome and Firefox, it appears differently in IE: To address this issue in IE, you may need to make adjustments to the CSS styles specifically for that browser. One potential solution could involve creating a separat ...

What is causing the text to not wrap around properly?

I'm currently facing an issue where the text that should not wrap around the image is wrapping, while the text that should be wrapped isn't. This is causing a layout problem in my coding section as shown here: The desired layout is to have the i ...

Executing a Javascript function through Typescript in an Ionic application

I integrated a plugin into my ionic project, which includes both Java and JS code: cordova.define("cordova-sms-plugin.Sms", function(require, exports, module) { 'use strict'; var exec = require('cordova/exec'); var sms = {}; functio ...

There was no popcorn mix-up in your document

Encountering an issue while using grunt for staging (grunt serve): Running "bower-install:app" (bower-install) task popcornjs was not injected into your file. Please check the "app\bower_components\popcornjs" directory for the required file, an ...

What is the best way to incorporate this data into the HTML document?

I am an aspiring programmer who has self-taught programming and is now experimenting with Firebase Firestore. When attempting the following code: var docRef = db.collection("Marcus").doc("one") docRef.get().then(function(doc) { if (doc.exis ...

Redirecting files from the file system to the emulator is not functioning properly

I am new to Phonegap and need help resolving this issue. In my application, I need to redirect to the List.html file when a button is clicked. Here is the code I have written: button1 function test() { window.location="/home/swift-03/phonegapexa ...