Horje
How to Disable Input in JavaScript ?

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




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Convert String to Date in TypeScript ? How to Convert String to Date in TypeScript ?
JavaScript Program to Copy all Nodes of a Linked List JavaScript Program to Copy all Nodes of a Linked List
How to Format the Labels of the Y Axis in a Chart ? How to Format the Labels of the Y Axis in a Chart ?
JavaScript Program to Find N Largest Elements from a Linked List JavaScript Program to Find N Largest Elements from a Linked List
How to Create Interface with Self-Reference Property in TypeScript ? How to Create Interface with Self-Reference Property in TypeScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13