Switch Textbox to readonly in runtime
You can toggle the textbox to read-only or editable mode by using its readOnly property.
jquery code snippet:
textbox.prop("readonly", true);
javascript code snippet:
textbox.readOnly = true;
Make textbox readonly – Full HTML & Scripts
Here’s a complete HTML code example that changes the behavior of textbox based on readonly property. You can use either jQuery or Javascript:
HTML Structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Readonly Textbox Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Readonly Textbox Example</h1>
<label for="readonly-textbox">Readonly Textbox:</label>
<input type="text" id="readonly-textbox" value="This is a readonly textbox">
<button id="make-readonly">Make Readonly</button>
<button id="make-editable">Make Editable</button>
</div>
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
CSS (styles.css):
.container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
text-align: center;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
}
button {
padding: 10px 20px;
margin: 10px;
cursor: pointer;
}
Using JQuery (script.js)
$(document).ready(function() {
// Get a reference to the textbox
var textbox = $("#readonly-textbox");
// Make the textbox readonly
$("#make-readonly").click(function() {
textbox.prop("readonly", true);
});
// Make the textbox editable
$("#make-editable").click(function() {
textbox.prop("readonly", false);
});
});
we use jQuery to handle the click events of the “Make Readonly” and “Make Editable” buttons. When the “Make Readonly” button is clicked, we set the readonly property of the textbox to true, making it readonly. When the “Make Editable” button is clicked, we set the readonly property to false, allowing the user to edit the textbox.
Using Javascript (script.js)
document.addEventListener("DOMContentLoaded", function() {
// Get a reference to the textbox
var textbox = document.getElementById("readonly-textbox");
// Get references to the buttons
var makeReadonlyButton = document.getElementById("make-readonly");
var makeEditableButton = document.getElementById("make-editable");
// Function to make the textbox readonly
function makeReadonly() {
textbox.readOnly = true;
}
// Function to make the textbox editable
function makeEditable() {
textbox.readOnly = false;
}
// Attach click event handlers to the buttons
makeReadonlyButton.addEventListener("click", makeReadonly);
makeEditableButton.addEventListener("click", makeEditable);
});
This JavaScript code achieves the same functionality – It uses the addEventListener method to attach click event handlers to the “Make Readonly” and “Make Editable” buttons and updates the readOnly property of the textbox accordingly.