Open In App

How to use input readonly attribute in jQuery ?

Use jQuery methods to add the readonly attribute to the form input field.

Example 1: In this example the read-only attribute of form input text field is enabled by using attr() method.




<!DOCTYPE HTML> 
<html
    <head
        <title
            Add a readonly attribute to an input field
        </title>
          
        <script src
        </script>
    </head
      
    <body style = "text-align:center;"
      
        <h1 style = "color:green;"
            GeeksForGeeks 
        </h1>
          
        <p style = "font-size: 15px; font-weight: bold;">
            The readonly attribute is added to input box
            on click on the button.
        </p>
          
        <form>
            Input : <input type="text" name="input_field" />
        </form>
        <br>
          
        <button onclick = "GFG_Run()">
            click here
        </button>
          
        <p id = "GFG_down" style
            "color: green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script>
            function GFG_Run() {
                  
                $('input').attr('readonly', true);
                document.getElementById("GFG_down").innerHTML 
                        = "Read-Only attribute enabled";
            }
        </script
    </body
</html>                    

Output:

Example 2: In this example the read-only attribute of form input text field is enabled by using prop() method .




<!DOCTYPE HTML> 
<html
    <head
        <title
            Add a readonly attribute to an input tag
        </title>
          
        <script src
        </script>
    </head
      
    <body style = "text-align:center;">
           
        <h1 style = "color:green;"
            GeeksForGeeks 
        </h1>
          
        <p style = "font-size: 15px; font-weight: bold;">
            The readonly attribute is added to input box
            on click on the button.
        </p>
          
        <form>
            Input : <input type="text" name="input_field" />
        </form>
        <br>
          
        <button onclick = "GFG_Run()">
            click here
        </button>
          
        <p id = "GFG_down" style
            "color: green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script>
            function GFG_Run() {
                $('input').prop('readonly', true);
                document.getElementById("GFG_down").innerHTML
                        = "Read-Only attribute enabled";
            }
        </script
    </body
</html>                    

Output:

jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.


Article Tags :