Is there a way to detect when the disabled attribute of an input changes in JQuery. I want to toggle the style based on the value.
I can copy/paste the same enable/
You can take advantage of your layout and make all of your handlers find things relatively, shortening all your current code this:
$(function() {
$("input:disabled").addClass("disabled");
$(":radio").change(function() {
var disabled = this.checked && this.value == "No";
$(this).siblings("div").find("input")
.attr('disabled', disabled)
.toggleClass('disabled', disabled);
});
});
You can view a demo here, also since you know which class, elements and whether you want it on or off, you can use .toggleClass(class, bool) to shorten things up a but further. If you want this to be more precise, you can give those radio buttons a class, for example:
<input type="radio" name="Group1" id="Radio1" value="Yes" class="toggler" />
Then you can do $(".toggler")
instead of $(":radio")
, same for the div
, you could give it a class and do .siblings(".fields")
instead of .siblings("div")
...the point is if your layout is consistent, use that to your advantage when DRY coding.
Although there are more efficient ways of tackling this problem, one way of handling this is by running a function every xx seconds that will set the required CSS classes on disabled elements:
window.setInterval(1000,function() {
$("input:disabled").addClass("disabled");
$("input:enabled").removeClass("disabled");
});
This will check all input elements every second. But again, this is a VERY bad solution. You would be better off restructuring your code.
Without changing too much of your code and HTML, I would do something like this (didn't test it though):
$("input[name^=Group]").change(function () {
var disabled = ($(this).val() == "No") ? "disabled" : "";
var groupName = $(this).attr("name");
$("#" + groupName + "Fields input")
.attr("disabled", disabled)
.addClass("disabled");
//remove disabled style to all enabled controls
$("input:enabled)").removeClass("disabled");
});
I assume that you want to enable the text inputs in the same fieldset, eh? Give this a try:
$('input[type="radio"]').change(function() {
if (this.value == "No") {
$('input[type="text"]', $(this).parents('fieldset')).attr('disabled', 'disabled');
} else {
$('input[type="text"]', $(this).parents('fieldset')).attr('disabled', '');
}
});
After further researching this issue, I stumbled upon a blog post by Rick Strahl in which we demonstrates a jQuery plug-in that allows for monitoring of CSS properties: jQuery CSS Property Monitoring Plug-in updated