Javascript: enabling and disabling form field elements

Here's another useful function for enabling and disabling your form elements using javascript.

Disabling all form elements

HTML form elements have an attribute called disabled that can be set using javascript. If you are setting it in HTML you can use disabled="disabled" but if you are using javascript you can simply set the property to true or false.

/* code from qodo.co.uk */ 
function toggleFormElements(bDisabled) { 
    var inputs = document.getElementsByTagName("input"); 
    for (var i = 0; i < inputs.length; i++) { 
        inputs[i].disabled = bDisabled;
    } 
    var selects = document.getElementsByTagName("select");
    for (var i = 0; i < selects.length; i++) {
        selects[i].disabled = bDisabled;
    }
    var textareas = document.getElementsByTagName("textarea"); 
    for (var i = 0; i < textareas.length; i++) { 
        textareas[i].disabled = bDisabled;
    }
    var buttons = document.getElementsByTagName("button");
    for (var i = 0; i < buttons.length; i++) {
        buttons[i].disabled = bDisabled;
    }
}

Disabling a single form element

But what if you just want to disable a single form element? Well, it's dead easy. Simply give your form element a unique id: -

<input type="text" name="age" id="age" />

And using JavaScript, you can disable that element quite easily using -

document.getElementById("age").disabled = true;


Comments 9

  1. thankx for the script sangesh
  2. This script doesn't seem to work with IE7, any solutions? Matt
  3. Are you sure you are using it correctly? When I use the example http://www.qodo.co.uk/wp-content/uploads/2007/08/toggleformelements.html it works perfectly fine for me in IE6 and 7. Stewart
  4. this code if I am applying to a button is not working. can you help me by applying the code to a button. Thanks in advance satya satya
  5. Hi Satya, try:
    <input type="button" value="Disable all" onclick="toggleFormElements(true)" />
    Stewart
  6. Thank you! JoycleCycle
  7. Thanks for the script man. I was trying something like document.forms[0].disabled=true for disabling an entire form. though from the display it looked like the form has been disabled, but when i clicked any button,it was doing the corresponding action. i tried ur script,worked fine wth me. just out of inquisitiveness, any idea as to why the document.forms[0].disabled=true didn't work?? Anirban
  8. Hi Anirban, As far as I know you cannot disable an entire form tag, you have to disable every element within it. I think it might look like it works in IE but it is not supposed to! Hope this helps. Stewart
  9. Thanks a lot for the script. This helped me fix a major display problem that I was facing with IE. dranga
  1. 1

Got something to say?

Join the discussion! You know how these things work; enter your details and comments below and be heard.

  1. Allowed tags: <b><i><br>