views:

65

answers:

4

Hi, I want to disable writing in an input type text using javascript. The input type text is populated from database that is why I don't want the user to modify its value.

Thinks for help.

+1  A: 

Get a reference to your input box however you like (eg document.getElementById('mytextbox')) and set its readonly property to true:

myInputBox.readonly = true;

Alternatively you can simply add this property inline (no JavaScript needed):

<input type="text" value="from db" readonly="readonly" />
Roatin Marth
If you're writing HTML (as opposed to XHTML) that'd be <input type="text" value="from db" readonly>
Olly Hodgson
+1  A: 

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 disabled or readonly attributes (if you want to remove it from the submit as well) to the <input>, like this:

<input type="text" disabled="disabled" />
//or...
<input type="text" readonly="readonly" />
Nick Craver
thank you for your help
kawtousse
+5  A: 

If the data is populated from the database, you might consider not using an <input> tag to display it. Nevertheless, you can disable it right in the tag:

<input type='text' value='${magic.database.value}' disabled>

If you need to disable it with Javascript later, you can set the "disabled" attribute:

document.getElementById('theInput').disabled = true;

The reason I suggest not showing the value as an <input> is that, in my experience, it causes layout issues. If the text is long, then in an <input> the user will need to try and scroll the text, which is not something normal people would guess to do. If you just drop it into a <span> or something, you have more styling flexibility.

Pointy
Bear in mind disabled can make text almost unreadable on some browsers. You might be better off with the readonly attribute, e.g. <input type="text" value="foo" readonly>
Olly Hodgson
Yes, that's a good point!
Pointy
many thanks for your constructive help;it save my time.
kawtousse
+1  A: 
document.getElementById('foo').disabled = true;

EDIT

or

document.getElementById('foo').readOnly = true;

Note that readOnly should be in CamelCase to work correctly in Firefox (magic).

hudolejev