jquery
  1. jquery-prop

JQuery prop()

The prop() method in jQuery is used to get or set properties of an HTML element. It is a shorthand method for the attr() method and should be used for properties such as checked, disabled, selected, and readonly attributes.

Syntax

Here is the syntax for using the prop() method:

$(selector).prop(propertyName, value)
  • selector - the HTML element(s) to be selected
  • propertyName - the name of the property to be set or retrieved
  • value (optional) - the value to be set for the property

Use

The prop() method is commonly used when working with form elements. For example, it can be used to check if a checkbox is checked, disable a form field, or select an option in a dropdown list.

Example

Here is an example of using the prop() method to set the disabled property of a form field:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Disable Input Fields with jQuery .prop()</title>
    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

    <label for="input1">Input 1:</label>
    <input type="text" id="input1"><br>

    <label for="input2">Input 2:</label>
    <input type="text" id="input2"><br>

    <label for="input3">Input 3:</label>
    <input type="text" id="input3"><br>

    <button id="disableInputsBtn">Disable Inputs</button>

    <script>
        $(document).ready(function() {
            // Attach a click event handler to the button
            $('#disableInputsBtn').click(function() {
                // Disable all input fields on the page
                $('input').prop('disabled', true);
            });
        });
    </script>
</body>
</html>
Try Playground

In this example, when the button is clicked, all input fields on the page will be disabled. The prop() method is used to set the disabled property of the input elements to true.

Summary

The prop() method in jQuery is a useful and convenient way to get or set properties of HTML elements. It is commonly used for form elements and makes it easy to check if a checkbox is checked, disable a form field, or select an option in a dropdown list. Try using the prop() method in your next jQuery project!

Published on: