Get the App
SLTechnology News&Howtos  ›  Development  › 

How to set the attribute value with the .prop () method

Shulou Source: shulou.com Published: 2022-06-01 07:34:31 10月06日 Update

Editor to share with you how to use the .prop () method to set attribute values, I hope you will learn something after reading this article, let's discuss it together!

.prop (propertyName, value) description: sets one or more attributes (properties) for matching elements.

The .prop () method is very convenient to set property values, especially if you need to set multiple property values using one function or multiple property values at once. This method must be used when setting selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, or defaultSelected. Starting with jQuery1.6, these properties can no longer be set using the .attr () method. They have no corresponding attributes, only property.

The Properties attribute generally affects the dynamic state of the DOM element and does not change the serialized HTML attribute attribute. For example, the value attribute of the input element, the disabled attribute of the input and button elements, and the checked attribute of the checkbox. Instead of using the .attr () method, you should use the .prop () method to set the disabled and checked properties. The .val () method should be used to access the value value.

("input") .prop ("disabled", false)

("input") .prop ("checked", true)

$("input") .val ("someValue")

Also note that the .removeProp () method should not be used to set these properties to false. Once the native attribute is removed, it can no longer be added. See. RemoveProp () for more information.

Computed property values (calculated attribute value)

By using a function to set properties, you can calculate its value based on the properties of other elements. For example, toggle all check boxes based on individual values:

$("input [type = 'checkbox']") .prop ("checked", function (I, val) {

Return! val

})

Note: if the set function does not return (that is, function (index, prop) {}), or returns undefined, the current value will not be changed. This is useful when certain conditions are met to set attribute values for selective elements (such as check boxes, radio selections, etc.).

After reading this article, I believe you have a certain understanding of "how to use the .prop () method to set property values". If you want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Attributes methods elements functions multiple more articles check boxes one-time information dynamic only finished sequence case buttons useful condition state knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Docker OPPO Reno Xiaomi Microsoft