16
votes

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(){
    if ($("#menuContinenti").attr("disabled")) {
        $("#menuContinenti").removeAttr("disabled");
    } else {
        $("#menuContinenti").attr("disabled", "disabled");
    }
});

Is this the best way or is there something like a .toggle() function to switch between disabled/enabled?

3
If it is not broken...don't fix it :)Nope
@FrançoisWahl yes it does work (as i wrote), but is this the best way to attemp this task? I hope jquery offers something like a .toggle() function to switch between boolean attributes like disabledNaigel
jQuery has a toggle but only to toggle visibility: api.jquery.com/toggle I don't know of a jQuery build-in toggle for disable/enable but you can have a look at all of the effects in their docs: api.jquery.com/category/effectsNope

3 Answers

46
votes

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);
8
votes

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

1
votes

you can check using $.is function like below

$("#filtri").change(function(){
    $("#menuContinenti").attr("disabled", ! $(this).is(':checked'));    
});