jQuery Tutorial Tutorials - jQuery .prop() method

jQuery .prop() method with example

The .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.

jQuery .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.

example

return true if the element is checked,otherwise return false

$('input[type="checkbox"').prop('checked');

Try now

.prop(propertyName,value)

Add/Set a simple property for the set of matched elements.

example

Disable and check all checkboxes on the page.

$( "input" ).prop( "disabled", false );
$( "input" ).prop( "checked", true );

Try now

.prop(propertyName,function)

Add/Set a simple property for the set of matched elements.
function will return a value to set for the property.

example

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;
});

Try now

.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 }.

example

Set the properties for all checkboxs.

$( "input[type='checkbox']" ).prop({  disabled: true});

Try now

Attributes vs. Properties

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
Date:2019-08-19 15:35:56 From:www.Lautturi.com author:Lautturi