Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to disable/enable an input box with jQuery?
We can easily disable input boxes (textbox, textarea) using the disabled attribute. When an input element is disabled, users cannot interact with it, and it won't be included in form submissions.
Using attr() and removeAttr() Methods
To disable an input element −
$('elementname').attr('disabled', 'disabled');
To enable a disabled element, we need to remove the "disabled" attribute from the element −
$('elementname').removeAttr('disabled');
Using prop() Method (Recommended)
jQuery also provides the prop() method which is recommended for boolean attributes like disabled −
// To disable
$('elementname').prop('disabled', true);
// To enable
$('elementname').prop('disabled', false);
The prop() method is preferred because it works directly with the DOM property rather than the HTML attribute, providing more reliable results across different browsers.
Complete Example
Here's a complete working example demonstrating how to disable and enable an input box using buttons −
<!DOCTYPE html>
<html>
<head>
<title>Enable/Disable Input Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.container {
padding: 20px;
font-family: Arial, sans-serif;
}
input {
padding: 10px;
margin: 10px 0;
font-size: 16px;
width: 200px;
}
button {
padding: 8px 16px;
margin: 5px;
font-size: 14px;
cursor: pointer;
}
input:disabled {
background-color: #f5f5f5;
color: #666;
}
</style>
</head>
<body>
<div class="container">
<h3>jQuery Enable/Disable Input Demo</h3>
<input type="text" id="tt1" placeholder="Enter some text" /><br>
<button type="button" id="btn1">Disable Input</button>
<button type="button" id="btn2">Enable Input</button>
<script>
$(document).ready(function () {
$('#btn1').click(function () {
$('#tt1').prop('disabled', true);
});
$('#btn2').click(function () {
$('#tt1').prop('disabled', false);
});
});
</script>
</div>
</body>
</html>
Key Features
In this example −
- The Disable Input button sets the
disabledproperty totrue - The Enable Input button sets the
disabledproperty tofalse - We target the specific input using its ID
#tt1for precise control - CSS styling provides visual feedback when the input is disabled
Multiple Elements
You can also disable multiple elements at once using class selectors −
// Disable all inputs with class 'form-input'
$('.form-input').prop('disabled', true);
// Enable all text inputs
$('input[type="text"]').prop('disabled', false);
Conclusion
Using jQuery's prop() method is the recommended approach for controlling the disabled state of input elements. The attr() and removeAttr() methods also work but prop() provides better browser compatibility and performance for boolean properties like disabled.
