Search Qodo.co.uk

Javascript: enabling and disabling form field elements

Here’s another useful function for enabling and disabling your form elements using javascript. This function can be used to disable form elements when a user has submitted a form to stop them submitting it again.

Disabling all form elements

/* 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;

Download

Download the Javascript: enabling and disabling form field elements example.

Post Details

Blog Archives

Blog Categories

Comments

5 Responses to “Javascript: enabling and disabling form field elements”

thankx for the script


  • Posted by Matt
  • Permalink

This script doesn’t seem to work with IE7, any solutions?


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.


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


Hi Satya, try:

<input type="button" value="Disable all" onclick="toggleFormElements(true)" />

Leave Feedback

Your comments