Monitoring DOM Changes in JQuery

前端 未结 4 1006
予麋鹿
予麋鹿 2021-01-14 21:14

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/

4条回答
  •  心在旅途
    2021-01-14 21:59

    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:

    
    

    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.

提交回复
热议问题