Monitoring DOM Changes in JQuery

Posted by user363866 on Stack Overflow See other posts from Stack Overflow or by user363866
Published on 2010-06-10T19:30:58Z Indexed on 2010/06/10 19:32 UTC
Read the original article Hit count: 325

Filed under:
|

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/disable code for each change event (as I did below) but I was looking for a more generic approach.

Can I create a custom event that will monitor the disabled attribute of specified inputs?

Example:

 <style type="text/css">.disabled{ background-color:#dcdcdc; }</style>


<fieldset>
    <legend>Option 1</legend>
    <input type="radio" name="Group1" id="Radio1" value="Yes" />Yes
    <input type="radio" name="Group1" id="Radio2" value="No" checked="checked" />No
    <div id="Group1Fields" style="margin-left: 20px;">
        Percentage 1:
        <input type="text" id="Percentage1" disabled="disabled" /><br />
        Percentage 2:
        <input type="text" id="Percentage2" disabled="disabled" /><br />
    </div>
</fieldset>
<fieldset>
    <legend>Option 2</legend>
    <input type="radio" name="Group2" id="Radio3" value="Yes" checked="checked" />Yes
    <input type="radio" name="Group2" id="Radio4" value="No" />No
    <div id="Group2Fields" style="margin-left: 20px;">
        Percentage 1:
        <input type="text" id="Text1" /><br />
        Percentage 2:
        <input type="text" id="Text2" /><br />
    </div>
</fieldset>
<script type="text/javascript">
    $(document).ready(function () {

        //apply disabled style to all disabled controls
        $("input:disabled").addClass("disabled");

        $("input[name='Group1']").change(function () {
            var disabled = ($(this).val() == "No") ? "disabled" : "";
            $("#Group1Fields input").attr("disabled", disabled);

            //apply disabled style to all disabled controls
            $("input:disabled").addClass("disabled");

            //remove disabled style to all enabled controls
            $("input:not(:disabled)").removeClass("disabled");

        });
        $("input[name='Group2']").change(function () {
            var disabled = ($(this).val() == "No") ? "disabled" : "";
            $("#Group2Fields input").attr("disabled", disabled);

            //apply disabled style to all disabled controls
            $("input:disabled").addClass("disabled");

            //remove disabled style to all enabled controls
            $("input:not(:disabled)").removeClass("disabled");
        });           

    });
</script>

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about javascript-events