Home > Web Front-end > JS Tutorial > body text

How to Correctly Enable Input Elements with jQuery Using prop()

Susan Sarandon
Release: 2024-10-19 19:05:02
Original
189 people have browsed it

How to Correctly Enable Input Elements with jQuery Using prop()

Removing "disabled" Attribute Using jQuery

In your query, you seek to first disable and then enable input elements upon clicking a link. However, your code fails to remove the "disabled" attribute.

jQuery's prop() Method

To effectively disable or enable elements in jQuery, invariably employ the prop() method. This distinction matters since prop() deals with properties, whereas attr()/removeAttr() handles attributes.

In your particular instance, the correct code would be:

$("#edit").click(function(event){
   event.preventDefault();
   $('.inputDisabled').prop("disabled", false); // Elements are now enabled.
});
Copy after login

See the updated code in action at this jsFiddle: [link to jsFiddle]

Prop() vs. attr()/removeAttr()

While attr()/removeAttr() can technically enable/disable elements, it's not recommended due to potential inconsistencies. Prop() explicitly manages property values, providing more reliable behavior.

Pre-jQuery 3.0 (before 2016)

removeAttr() removed the disabled attribute entirely, setting the property to false. Conversely, prop() only modified the property's boolean value.

jQuery 3.0 and Later

prop() remains the recommended approach, as removeAttr() now no longer sets the corresponding property to false. This distinction is essential for modern browsers that differentiate between attributes (initial values) and properties (current values).

The above is the detailed content of How to Correctly Enable Input Elements with jQuery Using prop(). For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!