I want to disable writing in an input field of type text
using JavaScript, if possible. The input field is populated from a database; that is why I don't want the user to modify its value.
The disabled attribute is a boolean attribute. When present, it specifies that the <input> element should be disabled. A disabled input element is unusable and un-clickable.
Definition and Usage The disabled attribute is a boolean attribute. When present, it specifies that the element should be disabled. A disabled element is unusable. The disabled attribute can be set to keep a user from using the element until some other condition has been met (like selecting a checkbox, etc.).
You can't disable a textbox in CSS. Disabling it is not a presentational task, you will have to do this in the HTML markup using the disabled attribute.
document.getElementById('foo').disabled = true;
or
document.getElementById('foo').readOnly = true;
Note that readOnly
should be in camelCase to work correctly in Firefox (magic).
Demo: https://jsfiddle.net/L96svw3c/ -- somewhat explains the difference between disabled
and readOnly
.
If you know this when the page is rendered, which it sounds like you do because the database has a value, it's better to disable it when rendered instead of JavaScript. To do that, just add the readonly
attribute (or disabled
, if you want to remove it from the form submission as well) to the <input>
, like this:
<input type="text" disabled="disabled" /> //or... <input type="text" readonly="readonly" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With