Thursday, May 5, 2011

How can I Enable\Disable all subcontrols of a table?

Hi,

I have a checkBox, which when it's checked i want to enable a table and its subcontrols and when it's disabled I want to do the opposite.

I have already understand that I have to iterate all subControls of the table, and my question is if there is any nice and generic way of doing it.

Thanks in advance,

oz.

From stackoverflow
  • It's a lot easier to do with with a selector and a class name using a framework, for example (using Prototype.js).

    When this item is clicked, enable all items with class of 'mycontrols'.

    $('containerDiv').select('.mycontrols').each(function(element){element.disabled=false})
    
  • You can do this with jQuery. Let's say that your HTML looks like this:

    <input type="checkbox" onclick="toggleControls(this)"/>Controls Disabled
    <table id="myTable">
     <tr>
      <td>Name: <input type="text" /></td>
      <td>Select: <input type="radio" /></td>
     </tr> .....
    

    The toggleControls() function to disable/enable all the controls inside the table (this means all textboxes, buttons, checkboxes, radio buttons and dropdowns) looks like this:

    <script>
       function toggleControls(e){
         $('#myTable input,select,textarea').attr('disabled',e.checked);
       }
    </script>
    

    jQuery's css selectors make that one line to disable/enable the controls possible. With plain old javascript, the function would look like this:

    var myTable = document.getElementById("myTable");
    var controls= myTable.getElementsByTagName("input"); 
    // Repeat the previous line for "select" and "textarea"
    for(i = 0; i < controls.length; i++) {
        control = controls[i];
        control.disabled = !control.disabled;        
    }
    
    oz radiano : How can I iterate the sub tables inside the main table? they have no tagName
    Jose Basilio : Are you going to use plain javascript or jQuery? Can you post your HTML, so that I can a better idea of what your are trying to accomplish?
    Jose Basilio : For the jQuery way, just add a selection of $("#myTable table'), this will get all the subtables within the table that has an ID. For plain old javascript, myTable.getElementsByTagName("table") would do the same.

0 comments:

Post a Comment