Reading and Modifying Properties
In this page:
Reading Properties
The prop() method reads the live DOM property value, like checked or disabled, which can differ from the attribute originally written in the HTML. For example, a checkbox's checked attribute never changes once loaded, but its checked property updates as the user clicks it.
Example: Reading Properties
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="check" type="checkbox" checked>
<script>
console.log($("#check").prop("checked"));
</script>
</body>
</html>
Setting Properties
Use prop() to change boolean DOM properties such as checked, disabled, or selected. Passing true or false directly toggles the actual behavior of the element, not just its outward markup.
Example: Setting Properties
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="check" type="checkbox">
<script>
$("#check").prop("checked", true);
</script>
</body>
</html>
Toggle Properties
You can read a property's current value and then set it to the opposite with prop(), a common pattern for toggle buttons like 'select all' checkboxes. Reading before writing lets your code react to whatever state the user left the element in.
Example: Toggle Properties
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="check" type="checkbox">
<button id="btn">Toggle</button>
<script>
$("#btn").on("click", function() {
$("#check").prop("checked", !$("#check").prop("checked"));
});
</script>
</body>
</html>
Selected Option
prop() can read the selected state of form option elements, letting you check which option in a select is currently chosen. This is more reliable than trying to read the value attribute, since the selection can change without touching the markup.
Example: Selected Option
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<select id="color"><option>Red</option><option selected>Blue</option></select>
<script>
console.log($("#color option:selected").text());
</script>
</body>
</html>
Property and Attribute
For live form state -- checked, disabled, selected -- prop() is usually the right choice, since it reflects what's actually happening in the browser right now. Reach for attr() only when you specifically need the original HTML-authored value.
Example: Property and Attribute
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="check" type="checkbox" checked>
<script>
console.log("Live state:", $("#check").prop("checked"));
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: