Tuesday, March 6, 2012

Disable div contents with javascript

It is a common requirement to disable ( not hide) div contents on client side depending on certain logic. For example if you have inputs like radio buttons in a div and you want to disable all of them within the given div, you can disable the div to disable selection of any element inside the div.

One way to achieve this via java script is to use the disable attribute.

$('div#myDiv').attr("disabled", 'disabled');

This works in all browsers except firefox. After trying different ways to do it I finally wrote a small script that iterates through your container element (div in this case) and disables them. This works in all browsers.

$('div#myDiv').children().each(function(i,element){

$(this).attr("disabled", 'disabled');
});

No comments: