how can I disable everything inside a form using javascript/jquery?

I have a form that pop up inside a layer, and I need to make everything inside that form read only regarding what type of input it is. Anyway to do so?


This is quite simple in plain JavaScript and will work efficiently in all browsers that support read-only form inputs (which is pretty much all browsers released in the last decade):

var form = document.getElementById("your_form_id");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
    elements[i].readOnly = true;
}

With HTML5 it's possible to disable all inputs contained using the <fieldset disabled /> attribute.

disabled:

If this Boolean attribute is set, the form controls that are its descendants, except descendants of its first optional element, are disabled, i.e., not editable. They won't received any browsing events, like mouse clicks or focus-related ones. Often browsers display such controls as gray.

Reference: MDC: fieldset


You can use the :input selector, and do this:

$("#myForm :input").prop('readonly', true);

:input selects all <input>, <select>, <textarea> and <button> elements. Also the attribute is readonly, if you use disabled to the elements they won't be posted to the server, so choose which property you want based on that.


Its Pure Javascript :

var fields = document.getElementById("YOURDIVID").getElementsByTagName('*');
for(var i = 0; i < fields.length; i++)
{
    fields[i].disabled = true;
}

You can do this the easiest way by using jQuery. It will do this for all input, select and textarea elements (even if there are more than one in numbers of these types).

$("input, select, option, textarea", "#formid").prop('disabled',true);

or you can do this as well but this will disable all elements (only those elements on which it can be applied).

$("*", "#formid").prop('disabled',true);


disabled property can applies to following elements:

  • button
  • fieldset
  • input
  • optgroup
  • option
  • select
  • textarea

But its upto you that what do you prefer to use.