Open In App

How to make a text input non-editable using jQuery ?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

An HTML document containing the input text area and the task is to make the text input non-editable with the help of jQuery. There are two approaches that are discussed below:

Approach 1:

We are going to set the property readonly to true. To set the readonly property, we will use a prop() method.

Example:

HTML
<!DOCTYPE HTML>
<html>

<head>
    <title>
        How to make a text input
        non-editable using JQuery?
    </title>

    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
</head>

<body style="text-align:center;">

    <h1 style="color:green;">
        GeeksForGeeks
    </h1>

    <p id="GFG_UP"></p>

    Type Here: <input id="input" />
    <br><br>
    
    <button onclick="GFG_Fun()">
        Click Here
    </button>
    
    <p id="GFG_DOWN"></p>

    <script>
        var el_up = document.getElementById('GFG_UP');
        var el_down = document.getElementById('GFG_DOWN');
        el_up.innerHTML = "Click on the button to "
                        + "perform the operation.";

        function GFG_Fun() {
            $("#input").prop("readonly", true);
            
            el_down.innerHTML = 
                "Input element is now read-only";
        }
    </script>
</body>

</html>

Output:

Approach 2:

We are going to set the property readonly to true. In this example, we will use attr() method to set the property value.

Example:

HTML
<!DOCTYPE HTML>
<html>

<head>
    <title>
        How to make a text input 
        non-editable using JQuery?
    </title>

    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
</head>

<body style="text-align:center;">

    <h1 style="color:green;">
        GeeksForGeeks
    </h1>

    <p id="GFG_UP"></p>

    Type Here: <input id="input" />
    <br><br>
    
    <button onclick="GFG_Fun()">
        Click Here
    </button>
    
    <p id="GFG_DOWN"></p>

    <script>
        var el_up = document.getElementById('GFG_UP');
        var el_down = document.getElementById('GFG_DOWN');
        el_up.innerHTML = "Click on the button to "
                        + "perform the operation.";

        function GFG_Fun() {
            $("#input").attr("readonly", true);
            el_down.innerHTML = 
                "Input element is now read-only";
        }
    </script>
</body>

</html>

Output:



Next Article

Similar Reads