Disable and enable an input text box with JavaScript/jQuery
This post will discuss how to disable and enable an input text box in JavaScript and jQuery.
When the element is disabled, it cannot accept clicks. To disable an input element, its disabled HTML attribute should be false.
1. Using jQuery
To set the input box disabled property to true or false with jQuery, you can use the .prop() function.
jQuery
|
1 2 3 4 5 6 7 8 9 10 11 12 |
$(document).ready(function() { var disabled = false; $('#submit').click(function() { if (disabled) { $("#name").prop('disabled', false); // if disabled, enable } else { $("#name").prop('disabled', true); // if enabled, disable } disabled = !disabled; }) }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Enter your name:</label> <input type="text" id="name" name="name"> </div> <button id="submit">Toggle</button> |
We can simplify the code to:
|
1 2 3 4 5 6 7 8 9 10 11 |
$(document).ready(function() { $('#submit').click(function() { var disabled = $("#name").prop('disabled'); if (disabled) { $("#name").prop('disabled', false); // if disabled, enable } else { $("#name").prop('disabled', true); // if enabled, disable } }) }); |
Alternatively, you can use the .attr() method to set the disabled attribute of the input element and .removeAttr() to remove the attribute from the input element.
jQuery
|
1 2 3 4 5 6 7 8 9 10 11 |
$(document).ready(function() { $('#submit').click(function() { var disabled = $("#name").attr('disabled'); if (disabled === undefined) { $("#name").attr('disabled', 'disabled'); } else { $("#name").removeAttr('disabled'); } }) }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Enter your name:</label> <input type="text" id="name" name="name"> </div> <button id="submit">Toggle</button> |
2. Using JavaScript
With plain JavaScript, you can use the disabled property of the actual DOM object to enable or disable the input.
JS
|
1 2 3 4 5 6 7 8 9 |
document.getElementById('submit').onclick = function() { var disabled = document.getElementById("name").disabled; if (disabled) { document.getElementById("name").disabled = false; } else { document.getElementById("name").disabled = true; } } |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Enter your name:</label> <input type="text" id="name" name="name"> </div> <button id="submit">Toggle</button> |
That’s all about enabling and disabling an input text box in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)