Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding readonly attribute to all form elements

Tags:

html

jquery

forms

I'm using jQuery to add a readonly attribute to all form elements but can't seem to figure out how to do this.

Here is what I'm trying:

$('#form1').each( function() { $(this).attr('readonly', true); }); 

I have a simple form using label/input to display form elements. Also I'm using tipsy (Tool tip plug-in) as well as Formalize (Look and Feel Plug-in)

like image 328
Phill Pafford Avatar asked Oct 26 '10 19:10

Phill Pafford


People also ask

How do you add a readonly attribute?

Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript. setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value. If the specified attribute already present, then the value is being set or changed.

How do you make all input fields read only?

Wrap the input fields and other stuff into a <fieldset> and give it the disabled="disabled" attribute. Pretty simple, this is the best client side solution so far.

How do I make a form element readonly?

The readonly attribute is a boolean attribute. When present, it specifies that an input field is read-only. A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it).


2 Answers

Try this:

$('#form1 input').attr('readonly', 'readonly'); 
  • You may want to include more elements #form1 input, #form1 textarea, #form1 select
  • In jQuery, you usually don't need to iterate over the collection. attr would work for a collection same as for a single element.
  • In your case, #form1 matched just the <form> element, and each was triggered once, for that element. To find all elements (input or not), you can write #form1 *.
like image 172
Kobi Avatar answered Sep 20 '22 22:09

Kobi


This is even better use the input selector. Also note Read only is only for input type of text and password and textarea . It will not work on select elements, radio, checkboxes, buttons. If you want to display but not allow them to type or click. Try using disabled.

$("#form1 :input").attr("disabled", true); 

Note: by using disabled it will grey out the input, select or textarea but will not post this element when submitted. If you need it to post let me know and I can help you out.

Here is a demo http://jsfiddle.net/j5PAn/

like image 21
John Hartsock Avatar answered Sep 20 '22 22:09

John Hartsock