Toggle input disabled attribute using jQuery

Tommy Arnold picture Tommy Arnold · Jan 15, 2011 · Viewed 181.8k times · Source

Here is my code:

$("#product1 :checkbox").click(function(){
    $(this)
        .closest('tr') // Find the parent row.
            .find(":input[type='text']") // Find text elements in that row.
                .attr('disabled',false).toggleClass('disabled') // Enable them.
                .end() // Go back to the row.
            .siblings() // Get its siblings
                .find(":input[type='text']") // Find text elements in those rows.
                .attr('disabled',true).removeClass('disabled'); // Disable them.
});

How do I toggle .attr('disabled',false);?

I can't seem to find it on Google.

Answer

Arne picture Arne · Feb 28, 2012
$('#el').prop('disabled', function(i, v) { return !v; });

The .prop() method accepts two arguments:

  • Property name (disabled, checked, selected) anything that is either true or false
  • Property value, can be:
    • (empty) - returns the current value.
    • boolean (true/false) - sets the property value.
    • function - Is executed for each found element, the returned value is used to set the property. There are two arguments passed; the first argument is the index (0, 1, 2, increases for each found element). The second argument is the current value of the element (true/false).

So in this case, I used a function that supplied me the index (i) and the current value (v), then I returned the opposite of the current value, so the property state is reversed.