Enable Disable group of HTML Elements with Checkbox using jQuery

On 5/25/2015

Enable/Disable group of HTML elements is fairly simple with jQuery. Any single element can be enabled/disabled via it's DOM property disabled. But how to do it in group? The idea is to wrap all the elements meant to be grouped in a <div> container and call jQuery's :input selector to select all the child elements of the container and set it's disabled property.


Let's see an example. Say we want to toggle some html elements based on a check box value.

HTML Markup
<input id="chk-student" type="checkbox"><label>Student</label>
<div id="details">
     <input id="name" type="text" />
     <select id="section">
          <option id="secA">Section A</option>
          <option id="secB">Section B</option>
     <textarea id="remarks"></textarea>

Now we have to enable the elements within container #details when the check box #chk-student is checked and disable when it is unchecked. It could be achieved with this jQuery code,

jQuery Code
$('#chk-student').change(function() {
     $('#details :input').attr('disabled', !this.checked);

Now everything is fine, except the elements are all enabled on page load and the checkbox is unchecked. So let us tweak the above jQuery function to disable the div container elements on page load like this,

     //disable on page load
     $('#details :input').attr('disabled', true);
     $('#chk-student').change(function() {
          $('#details :input').attr('disabled', !this.checked);

Note: The :input selector will select all the input elements of the parent container.

Last-Modified: May-25-2015

No comments:

Post a Comment

Contact Form


Email *

Message *