Open In App

How to Disable Input in JavaScript ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, disabling the input field mainly restricts the users from interacting with the input elements, and also prevents the modifications to the form elements such as buttons or input fields.

We can use various methods and attributes to disable the input.

Using disabled attribute

In this approach, we are using the disabled property of JavaScript to set the disabled attribute of the input field to render it in an uneditable form so that it cannot accept input from the users.

Syntax:

element.disabled = true;

Example: The below example uses a disabled attribute to disable input in JavaScript.

HTML




<!DOCTYPE html>
 
<head>
    <title>Example 1</title>
    <style>
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
    <h3>Using disabled attribute</h3>
    <input type="text" id="input1"
        value="GeeksforGeeks">
    <script>
        document.getElementById("input1").
        disabled = true;
    </script>
</body>
 
</html>


Output:

Screenshot-2024-02-27-at-11-27-46-Example-1

Using readOnly attribute

In this approach, we are using the JavaScript readOnly property to set the readOnly attribute to the input field. This makes the input field uneditable while visually indicating that it is in a read-only state and cannot be editable.

Syntax:

element.readOnly = true;

Example: The below example uses the readOnly attribute to disable input in JavaScript.

HTML




<!DOCTYPE html>
 
<head>
    <title>Example 2</title>
    <style>
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
    <h3>Using readOnly attribute</h3>
    <input type="text" id="input2"
        value="GeeksforGeeks">
    <script>
        document.getElementById("input2").
        readOnly = true;
    </script>
</body>
 
</html>


Output:

Screenshot-2024-02-27-at-11-29-07-Example



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads