Disable And Enable Input Elements In A Div Block Using jQuery

Today, we will learn how to toggle the 'disabled' attribute of input elements in a div block using jQuery.

The 'disabled' attributed is set to HTML input elements where user input is not desirable. When 'disabled' attribute is set to an input element, it is rendered read only. The read only input elements make lot of sense in various contexts.

<input type="text" name="elementName" disabled="disabled" />

Wouldn't it be more fun if we play around with the 'disabled' attribute programmatically? We are going to do exactly the same in this example.

You can see the example page here.

A sample text, checkbox, radio and select element is included in a div block. A button is provided to toggle the disabled attribute of the sample input elements. Let us examine the page and the solution in detail.

Let us first write the HTML head part.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
    <title>Tech Chorus - Hiding Input Elements In A Div With jQuery</title>

As the title suggests, we will make use of jQuery to manipulate the Document Object Model. Like many popular JavaScript libraries jQuery is available from a CDN. Let us make use of the jQuery Content Delivery Network to include the latest jQuery in our web page.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>          

Let us write a JavaScript function to handle the toggling and name it as toggleStatus.

<script type="text/javascript">

I'll explain what's going on in this part once we complete building the page.

function toggleStatus() {
    if ($('#toggleElement').is(':checked')) {
        $('#elementsToOperateOn :input').attr('disabled', true);
    } else {
        $('#elementsToOperateOn :input').removeAttr('disabled');
    }   
}

Close the 'head' section.

</script>
</head>

Start the 'body' tag.

<body>
<p>
This is our sample page. The article can be found at <a href="http://techchorus.net/disable-and-enable-input-elements-div-block-using-jquery">Tech Chorus</a>
</p>

Create the form and the checkbox element to handle toggling of 'disabled' attribute for the input elements in the div.

<form method="post" action="">
    <p>
        When you click the below button, all the input elements in the div are disabled, if they are enabled and vice versa.
    </p>
    <p>
    Click to change: <input id="toggleElement" type="checkbox" name="toggle" onchange="toggleStatus()" />
    </p>

Create the sample input elements and wrap it in a div. Also close the 'form', 'body' and 'html' tags.

 <div id="elementsToOperateOn">
        This is our example div block. <br />
        Sample Text Box: <input type="text" name="name" /> <br />
        Sample Checkbox : <input type="checkbox" name="participate" /> <br/>
        Sample Radio : <input type="radio" name="bookEarly" /> <br />
        Sample Select: <select name="sampleSelect">
                            <option>Option 1</option>
                            <option>Option 2</option>
                        </select>
    </div>
</form>
 
</body>
</html>

Discussion

Let us discuss the flow of the script. When the checkbox input element with id 'toggleElement' is clicked, the function toggleStatus() is fired.

Click to change: <input id="toggleElement" type="checkbox" name="toggle" onchange="toggleStatus()" />

We have defined the function toggleStatus() in the head section of the HTML document. Within the function toggleStatus() we check whether the element with id 'toggleElement' is checked.

$('#toggleElement').is(':checked')

jQuery provides wonderful DOM node selectors. $('#toggleElement') selects the node with id 'toggleElement'. You can use .is(':checked') to evaluate whether the input element is checked. If checked, we grab all the input elements within the div whose id is 'elementsToOperateOn' and set the attribute 'disabled' on all of them. To select all the input elements in the div we use:

$('#elementsToOperateOn :input')

To set the 'disabled' attribute on the selected nodes, we just use

.attr('disabled', true)

In our example page, we combine the above two code snippets to do more in less lines.

$('#elementsToOperateOn :input').attr('disabled', true);

Similarly, when the 'toggleElement' is not checked, we grab all the input elements in the div 'elementsToOperateOn' and remove the 'disabled' attribute. If you carefully observe the jQuery code, it is very much like English. Naturally, it is easier to remember the code that looks like English.

We are done with our first how to example on this site. In the coming days, I will publish more articles. I have actually drafted few already. Stay tuned.

About the author

Sudheer is an entrepreneur and software developer. Get more from Sudheer on Twitter.


Similarly, when the

Similarly, when the 'toggleElement' is not checked, we grab all the input elements in the div 'elementsToOperateOn' and remove the 'disabled' attribute. If you carefully observe the jQuery code, it is m=very much like English. Naturally, it is easier to remember the code that looks like English.

Thanks. Corrected the typo.

Thanks. Corrected the typo.

Sudheer
Binary Vibes

great! i changed it to

great!

i changed it to this:

if ( $("#preview").attr('hidden', true)){

$('#postform :input').attr('disabled', false);
}

Radio

Hi, very nice script, just what I'm looking for! So, I tried the same thing with a radio, but it didn't worked out...

Hope you can help me, Steven.

What happened when you tried?

What happened when you tried? Did you look for error messages in the firebug console?

Sudheer
Binary Vibes

Lovely post

Gotta love this site! keep it up :)

Enabling the form from disable status

Hi ,

Can it be done? I want to make the form disabled by default. When the Check box is checked then the form will be enabled.

Thanks,
Deb

Why not? Just remove the

Why not? Just remove the disabled attribute in all the input elements.

$('#elementsToOperateOn :input').removeAttr('disabled');

Sudheer
Binary Vibes

great!!! It solved my problem

great!!! It solved my problem

set checkbox on readonly

Can this be done in jquery?

I don't want to disable my checkbox as the value will not be comitted then.
So I want some sort of readonly on my checkbox, user cannot check/uncheck but value does get committed.

Sure. Replace 'disabled' with

Sure.

Replace 'disabled' with 'readonly' in our code.

function toggleStatus() {
    if ($('#toggleElement').is(':checked')) {
        $('#elementsToOperateOn :input').attr('readonly', true);
    } else {
        $('#elementsToOperateOn :input').removeAttr('readonly');
    }   
}

Sudheer
Binary Vibes

Fix for IE?

It doesnt work properly in IE7 (and 6 i assume).

I had tested the code snippet

I had tested the code snippet on IE 6 and 7 as well. What issue are you facing with them?

Sudheer
Binary Vibes

Hi there, great works,

Hi there,
great works, thanks.
Why there seems to be problem with IE? when you click on radio to disable it. It does not show the changes immediatly, unless you click on the page...
Please advise

When you click radio or

When you click radio or checkbox? What version of IE are you using?

Can you download the file from the Code Album git repository at http://github.com/bngsudheer/Code-Album/blob/master/web/js/jquery/div-di... and try it on your computer?

Sudheer
Binary Vibes

Thanks!

Hey !

Thank you for that. It helped me a lot.

I was looking for something

I was looking for something like this. Thanks!

I like this code

I like to use this code:

This is one area where I like to extend jQuery:

$.fn.disable = function() {
return this.each(function() {
if (typeof this.disabled != "undefined") this.disabled = true;
});
}

$.fn.enable = function() {
return this.each(function() {
if (typeof this.disabled != "undefined") this.disabled = false;
});
}

and then you can do:

$("#button").disable();
$("#button").enable();

I find myself disabling/enabling controls a lot.

How would I go about

How would I go about disabling fields for an option from a select drop down box?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.