Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toggle disabled attribute in jquery

Tags:

jquery

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?

like image 338
Naigel Avatar asked Aug 10 '12 14:08

Naigel


People also ask

How add and remove disabled property in jQuery?

To remove disabled attribute using jQuery, use the removeAttr() method. You need to first remove the property using the prop() method. It will set the underlying Boolean value to false.

How do I remove disabled attribute from button?

To remove the disabled attribute, select the element and call the removeAttribute() method on it, passing it disabled as a parameter, e.g. btn. removeAttribute('disabled') . The removeAttribute method will remove the disabled attribute from the element.

How do I add a disabled attribute?

To set the disabled attribute, select the element and call the setAttribute() method on it, passing it disabled as the first parameter, e.g. button. setAttribute('disabled', '') . The setAttribute method will add the disabled attribute to the element.

How check textbox is enabled or disabled in jQuery?

You can use $(":disabled") to select all disabled items in the current context. To determine whether a single item is disabled you can use $("#textbox1").is(":disabled") .


3 Answers

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);
like image 138
Explosion Pills Avatar answered Oct 31 '22 06:10

Explosion Pills


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

like image 36
Moin Zaman Avatar answered Oct 31 '22 07:10

Moin Zaman


you can check using $.is function like below

$("#filtri").change(function(){
    $("#menuContinenti").attr("disabled", ! $(this).is(':checked'));    
});
like image 37
Loken Makwana Avatar answered Oct 31 '22 06:10

Loken Makwana