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.

FOSS Project: 
Programming: 
Technology: 

Comments

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.

great!

i changed it to this:

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

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

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? Did you look for error messages in the firebug console?

Gotta love this site! keep it up :)

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 disabled attribute in all the input elements.


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

Hello,

I try this but its not working properly..... what i need i need by default it disabled and if i click on checkbox then my all values should be enable that's it..... but i tried its not working

looking for your reply
Adil

Can you post your code to a pastebin and paste the URL here?

What you have to do is:
1. Set the disabled attribute to disabled on your form elements
2. Change the JavaScript toggle code

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

I have included a demo page that does what you want.

great!!! It solved my problem

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 'readonly' in our code.


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

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

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

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 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?

Hi
I had the same problem - I found that when you check/uncheck the checkbox the changes don't happen immediately like in Firefox - you have to click on the page (anywhere) for it to apply.
Thank you in advance

Hey !

Thank you for that. It helped me a lot.

I was looking for something like this. Thanks!

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 disabling fields for an option from a select drop down box?

jquery is excellent addition it is good to use and easy to tackle it so it has more advantages.i found this informative and interesting blog so i think so its very useful and knowledge able.so it is great usability and good for us.so thanks for the nice post..so i appreciate to your efforts.

For a dropdown list, if only one value is present, that value showld be defaulted and if many values are present, default value should be null. Can you please provide the sample code for this

Hi, great coding, thank you very much.

FYI - I also have same issue using IE8.

'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...'

thanks you
You will have to crawl very nice,owe you gratitude..

How would i make this work???
I would like the Check Box to be disabled if Option 2 is selected in the drop down menu.

[code]

function toggleStatus() {
if ('#toggleElement.option.value == 2') {
$('#elementsToOperateOn :input').attr('disabled', true);
} else {
$('#elementsToOperateOn :input').removeAttr('disabled');
}
}

If you Select Option 2:

1
2
3

This becomes Disabled...

[/code]

The expression in if is slightly wrong.

It should be:


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

I am trying the same thing, though I am enabling two radio boxes when either one or another option is chosen (either temp or precip). It works the first time an option is selected, but if I try the dropdown box again, it doesn't reset to 'disabled'. Any suggestions?

Hiding Input Elements In A Div With jQuery

//time periods
function toggleStatus() {
if ( ($('#toggleElement').val() == 'temp') ||($('#toggleElement').val() == 'precip') ) {
$('#elementsToOperateOn :input').removeAttr('disabled', true);
$("#elementsToOperateOn p").removeClass('textdisabled');

} else {
$('#elementsToOperateOn :input').attr('disabled');
$("#elementsToOperateOn p").addClass('textdisabled');
}
}

.textdisabled {color:#999999;}

If you Select Option temp or precip:

--
temperature
precip
other

Montly Mean

This becomes Enabled...
Annual Mean
Climate Anomaly

@ sudheer on Fri, 08/27/2010 - 16:14.

I agree. Your code worked for me.

what i need i need by default it disabled and if i click on checkbox then my all values should be enable that's it..... but i tried its not working

Please show us the code you tried

First of all, thanks! This worked great and it was easy to set it up for disabled to be default and enable when the checkbox is clicked.

The trouble I ran into was having multiple instances, i.e. checkbox 1 enables div 1, and checkbox 2 enables div 2. The solution I came to was having two functions doing the same thing. I know...LAME. I don't know jquery or javascript well enough to write one function that can be used by both checkboxes and only enable the corresponding div. How could this code be adapted to do that?

Anyhow, thanks for this...it helped alot!

There's nothing wrong in writing 2 functions, especially when you are learning JavaScript and jQuery.

Try it. If you run into problem, feel free to post a comment here or in our forums.

why not use bind for the exampleS?

I tried your example page in IE7. It does not work.

Which version of IE? What doesn't work?

Thank you very much, you can combine this functionality with blockui plugin to cover some portions of the screen with a gray layer.

http://malsup.com/jquery/block/#element

Is there a way to access all the label elements within a div, rather than input elements?

trying like this $('#mydivid :label') gives exception..

thanks so much!

I love, love, love this. I wanted to make the text go gray with the inputs, so I put everything inside the div into a p tag and added and removed the css class to the p in the same function calls. Thanks so much for getting me started!

Tech Chorus - Hiding Input Elements In A Div With jQuery

function toggleStatus() {
if ($('#toggleElement').is(':checked')) {
$('#elementsToOperateOn :input').attr('disabled', true);
$("#elementsToOperateOn p").addClass('textdisabled');

}
else {
$('#elementsToOperateOn :input').removeAttr('disabled');
$("#elementsToOperateOn p").removeClass('textdisabled');

}
}

.textdisabled {color:#999999;}

This is our sample page. The article can be found at Tech Chorus

When you click the below button, all the input elements in the div are disabled, if they are enabled and vice versa.

Click to change:

This is our example div block.
Sample Text Box:
Sample Checkbox :
Sample Radio :
Sample Select:

Option 1
Option 2

$("#elementsToOperateOn").addClass('textdisabled');

would work with your first example. duh me.

hi.., i have just started to learn .net few times, so i am have no idea about this, but after read your post, i feel, it is really informative information. thanks

Very helpful. If anyone's looking for a plugin that does the job, here you go: http://s.technabled.com/jquery-foggle

how to dissable multiple butttons on a one button is that any one know about that plz help me......

can this be done via radio button?

Awesome - Thanks - saved a bunch of time.

Only problem was it wouldn't work on IE unless you clicked away from the checkbox afterwards.

Changed the onchange event to onclick and works like a charm!

Can you explain what you did? I am having the same problem in IE.

The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true);

And to enable again.

$myForm.find(':input:disabled').prop('disabled',false)

Hi ken,

does your solution solve the Internet explorer problem. i am using IE 7 but it seem not to be working. It's on permanent disable or permanent enabled, the switching doesn't work.

Also, how can this be used in a drop down select option. i have a situation whereby i have 5 DIV boxes and i have a drop down select box with 50 option to select. I want whereby based on selected option in the drop down select box, either of the anyone of the DIV will be enabled.

I will appreciate help.

This is exactly what I have been looking for! Thanks so much :)

Pages

Add new comment