I Have a text box and a control button next to it.Clicking on the button will call another function where some data is selected and written back to the text box.Currently my text box is editable by the user after the data is fetched to the text box.I want to make the text box read only after the user clicks on the button and fetches the data to the text box,So that now the data is present in the text box which cannot be edited.If the user has to change the data,the user has to again click on the button to call the function which will help us over write the data in the text box.How can I accomplish this in javascript.
Asked
Active
Viewed 3.8k times
4 Answers
7
you can do it like this
HTML:
<input type="text" id="mytextbox" value="click the button below."/>
<input type="button" value="click" onclick="changeText();"/>
Javascript:
function changeText(){
var text_box = document.getElementById('mytextbox');
if(text_box.hasAttribute('readonly')){
text_box.value = "This text box is editable.";
text_box.removeAttribute('readonly');
}else{
text_box.value = "This text box is read only.";
text_box.setAttribute('readonly', 'readonly');
}
}
fiddle example: http://jsfiddle.net/b7jAy/

dku.rajkumar
- 18,414
- 7
- 41
- 58
0
you can use jQuery .attr()
function to set the readonly status of the text field.
$('#textfield').attr('readonly', true);
$('#textfield').attr('readonly', 'readonly');

Hristo Petev
- 309
- 3
- 13
-
you should not consider that the OP is using jquery. – dku.rajkumar Feb 02 '12 at 08:11
0
Please try with JQuery. Thousands of reasons to use it as Javascript framework. Here is a response to your question:
Add "readonly" to <input > (jQuery)
Hope that helps,

Community
- 1
- 1

Ramon Araujo
- 1,743
- 22
- 31
0
Assign an id
attribute to the text box, say <input id=foo>
, and use
document.getElementById('foo').readOnly = true;

Jukka K. Korpela
- 195,524
- 37
- 270
- 390