Bluemarble
Bluemarble

Reputation: 2059

How to apply css on checkbox when it's getting disabled?

I have two chech Boxes (one of them disabled). I have replaced the check boxes with a div with background color with toggle function so that checked = green, unchecked = red.

HTML

<input type="checkbox" class="input_class_checkbox" disabled="disabled">    
<br/>
<input type="checkbox" class="input_class_checkbox">

JQUERY

$('.input_class_checkbox').each(function(){
$(this).hide().after('<div class="class_checkbox" />');

});

$('.class_checkbox').on('click',function(){
$(this).toggleClass('checked').prev().prop('checked',$(this).is('.checked'))
});

CSS

.class_checkbox {
width: 20px;  
height: 20px;
background-color: red;
}

.class_checkbox.checked {
  background-color: green;
}

 .class_checkbox.disabled {
  background-color: blue;
}

How do I apply this .disabled CSS on the disabled check box on page load? also check boxes can be disabled programmatically, so can I implement onDisabled kind of Jquery code to change the appearance when a check box is disabled?

Upvotes: 1

Views: 4059

Answers (3)

SW4
SW4

Reputation: 71160

Dont use Javascript*

You should ideally look to use HTML and CSS for this, without reliance on Javascript. This ensures correct separation of concerns (HTML = content, CSS = styling, JS = functionality). It is also a cleaner more performant solution.

input+span {
  height: 10px;
  width: 10px;
  display: inline-block;
  border: 1px solid;
}
input {
  display: none;
}
input:checked +span {
  background: lightgreen;
}
input:disabled + span {
  background: lightgrey;
}
<label>
  <input type="checkbox" />
  <span></span>
</label>

<label>
  <input type="checkbox" disabled />
  <span></span>
</label>

*Unless unavoidable

Upvotes: 1

Fernando Garcia
Fernando Garcia

Reputation: 1969

You need to write :disabled

Something like:

 .input_class_checkbox:disabled {
  background-color: blue;
}

Upvotes: 0

ketan
ketan

Reputation: 19341

I think you want something like:

$( "input:disabled" ).next().css( "background-color", "yellow" );

Check Fiddle

Upvotes: 3

Related Questions