toggle disabled attribute in jquery

前端 未结 3 866
臣服心动
臣服心动 2020-12-17 14:29

I\'ve a checkbox that enable or disable a select element

Actually I use this simple piece of code that works fine.

$(\"#filtri\").change(function(){
         


        
相关标签:
3条回答
  • 2020-12-17 14:58

    You should use .prop for disabled:

    $("#menuContinenti").prop('disabled', function () {
       return ! $(this).prop('disabled');
    });
    

    UPDATE: didn't realize the current property value is an argument to the function; this version is even cleaner:

    $("#menuContinenti").prop('disabled', function (_, val) { return ! val; });
    

    UPDATE: ES2015

    $("#menuContinenti").prop("disabled", (_, val) => !val);
    
    0 讨论(0)
  • 2020-12-17 14:58

    you can check using $.is function like below

    $("#filtri").change(function(){
        $("#menuContinenti").attr("disabled", ! $(this).is(':checked'));    
    });
    
    0 讨论(0)
  • 2020-12-17 15:08

    You can write your own plugin that does something like this.

    Add this after jQuery, in a script file preferably.

    (function($) {
        $.fn.toggleDisabled = function(){
            return this.each(function(){
                this.disabled = !this.disabled;
            });
        };
    })(jQuery);
    

    Then use it like this:

    $('#my-select').toggleDisabled();
    

    Courtesy: Toggle input disabled attribute using jQuery

    0 讨论(0)
提交回复
热议问题