14

How can we make all fields in a form read only ?

3 Answers 3

30

This should work:

$(':input').attr('readonly','readonly');

Or if you have a specific form...

$('#myFormID :input').attr('readonly','readonly');

If you are using just plain JavaScript, you'll want to do this.

var f = document.forms['myFormNAME'];
for(var i=0,fLen=f.length;i<fLen;i++){
  f.elements[i].readOnly = true;//As @oldergod noted, the "O" must be upper case
}

One side note... although you can "set" the readonly flag on checkbox and hidden input fields... it won't actually make them readonly.

Sign up to request clarification or add additional context in comments.

7 Comments

if I want to do only by javascript?
Why put jquery in the tags then.
if I want to do only by javascript you should learn JavaScript :)
f.elements[i].readonly = true; => f.elements[i].readOnly = true;
The upper code did not work with neither IE or Chrome for me and worked once I set the upcased 'O'. I am not top familiar with Js but it was I had to do to make it work here.
|
2

A solution without javascript, enclose all fields in fieldsets and add disabled tag to fieldsets.

1 Comment

Way better solution plus it suggests good practice by using fieldset to group related inputs
0

Another approach would be to add a readonly class to the parent element containing all input or textarea fields that need to be made readonly; and add the following in the css:

.readonly textarea,
.readonly input {
  pointer-events: none;
  background-color: gray;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.