Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable an input type=text?

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.

like image 487
kawtousse Avatar asked May 20 '10 14:05

kawtousse


People also ask

How do I disable input field typing?

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.

How do I disable text in HTML?

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.).

How do I disable a text box in CSS?

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.


2 Answers

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.

like image 114
hudolejev Avatar answered Sep 18 '22 11:09

hudolejev


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" /> 
like image 28
Nick Craver Avatar answered Sep 21 '22 11:09

Nick Craver