Skip to content Skip to sidebar Skip to footer

How To Change Color Of My Div If Check-box Is Checked?

I have table that is created based on records from data base. Inside of tbody I have tr that creates each table row. Table row has multiple time slots for same date. I want to chan

Solution 1:

Try this:

$('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><divclass="blockRow"><td>#StartTime#</td><td>#EndTime#</td><td><inputtype="checkbox"name="block"id="block"></td></div></cfoutput></tr></tbody></cfoutput>

jsfiddle:

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

This gets the closest blockrow to the current checkbox so should work with more than one instance. Since you can't have 2 elements with the same id I have change blockrow to the class.

If you want to do other things based on the same condition then you can do this:

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

Solution 2:

Easy:

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

EDIT

Then you don't include jQuery library. To make pure js make this:

http://jsfiddle.net/bfss81sa/

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

Here you are the complete 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";
      }
    });
  }
<inputtype="checkbox"name="block"id="block"><divid="box">
The box
</div>

Solution 3:

Your html code is a mess. Anyway, generally :

$('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');
 }
});

Of course, you can narrow the scope of input:checkbox selector. If it is not the FIRST <td> in your <tr> then you better assign it a class and get it with it.

NOTE : DOM must be correct <cfoutput> cannot be child of <tr>; <div> cannot have <td> as direct child; Incorrect DOM impact javascript traversing.

Post a Comment for "How To Change Color Of My Div If Check-box Is Checked?"