There is a way to achieve what you want without using jQuery or JavaScript.
If you place your <label>
tag next to the <input type=checkbox>
, you can apply a CSS selector like this:
/* selects the label immediately following a disabled input type=checkbox */
input[type=checkbox]:disabled+label {
/* changes its color to gray */
color: gray;
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('button').addEventListener('click', function(e) {
var cb = document.getElementById('cb');
cb.disabled = !cb.disabled;
});
});
input[type=checkbox]:disabled+label {
color: gray;
}
<div>
<input id='cb' type='checkbox' disabled> <label for='cb'>My checkbox</label>
</div>
<div>
<button>Toggle disabled</button>
</div>
Updated Solution
In response to your feedback, I have implemented a version using JavaScript to achieve your goal. However, I do not recommend this approach. Nonetheless, here is how it can be done:
document.addEventListener('DOMContentLoaded', function() {
var radios = document.getElementsByName('idRadio');
[].forEach.call(radios, function(radio, i) {
radio.addEventListener('change', function() {
var sp = document.getElementById('idSpecial');
sp.disabled = (this.value === "0");
sp.parentNode.removeChild(sp.nextSibling);
var span = document.createElement('span');
if (sp.disabled) span.style.color = 'gray';
span.textContent = 'Special';
sp.parentNode.insertBefore(span, sp.nextSibling);
});
});
});
<input type="checkbox" id="idSpecial" name="Special">Special
<input type="radio" value="1" name="idRadio" checked>Enable</input>
<input type="radio" value="0" name="idRadio">Disable</input>