.prop() method with exampleThe .prop() method in jQuery is used to get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.
.prop() method Syntax.prop([propertyName[,value|function]|[properties]) // That is .prop(propertyName) .prop(propertyName,value) .prop(propertyName,function) .prop(properties)
| Parameter | Type | Description |
|---|---|---|
propertyName |
String | the property name |
value |
Anything | a value to set for the property. |
function(index, oldPropValue) |
Function | a function returning the value to set. index is the position of the element in the set. oldPropValue is old property value. |
properties |
plainObject | an object of property-value pairs to set |
.prop(propertyName)Get the value of a property for the first element in the set of matched elements.
return true if the element is checked,otherwise return false
$('input[type="checkbox"').prop('checked');
.prop(propertyName,value)Add/Set a simple property for the set of matched elements.
Disable and check all checkboxes on the page.
$( "input" ).prop( "disabled", false ); $( "input" ).prop( "checked", true );
.prop(propertyName,function)Add/Set a simple property for the set of matched elements.
function will return a value to set for the property.
if the function return nothing or undefined. the checked value won't be changed.
//to toggle all checkboxes based off their individual values
$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
return !val;
});
.prop(properties)Add/Set one or more properties for the set of matched elements.
properties is an object of prop-value pairs,for example:
{ disabled: true } ,
{ disabled: true, checked: false }.
Set the properties for all checkboxs.
$( "input[type='checkbox']" ).prop({ disabled: true});
For <input type="checkbox" checked="checked" />
| method | result | why |
|---|---|---|
| elem.checked | true (Boolean) | Will change with checkbox state |
| $( elem ).prop( "checked" ) | true (Boolean) | Will change with checkbox state |
| elem.getAttribute( "checked" ) | "checked" (String) | Initial state of the checkbox; does not change |
| $( elem ).attr( "checked" ) (1.6) | "checked" (String) | Initial state of the checkbox; does not change |
| $( elem ).attr( "checked" ) (1.6.1+) | "checked" (String) | Will change with checkbox state |
| $( elem ).attr( "checked" ) (pre-1.6) | true (Boolean) | Changed with checkbox state |
