Search code examples
jquerytoggleattr

Toggle input disabled attribute using jQuery


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.


Solution

  • $('#el').prop('disabled', (i, v) => !v);
    

    The .prop() method gets the value of a property for the first element in the set of matched elements.

    Arguments
    • Property name (e.g. disabled, checked, selected) anything that can either be true or false
    • Property value, can be:
      • (empty) returns the current value.
      • boolean sets the property value.
    • function Is called for each matched element, the returned value is used to set the property. There are two arguments passed; the first argument is the index (number, starting with 0, 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.

    Additional information

    The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

    Attributes vs. Properties

    The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.