I have the following jQuery script that is used to manage a large treeview of inputs with the ability to enable/disable certain inputs. When a row is enabled, its textboxes should be enabled and vice versa.
UPDATE (Working)
This is my script:
<script type="text/javascript">
$(document).ready(function () {
$('#cb-master').click(toggleCheckAll);
$('#mappings input:checkbox[id^="cb"]').click(checkChildren);
$('#mappings tbody tr[id^="child"] input:checkbox').change(toggleInputs);
});
function toggleCheckAll() {
var selector = $(this).is(':checked')
? '#mappings tbody input:checkbox:checked'
: '#mappings tbody input:checkbox:not(:checked)';
$(selector).each(function () {
$(this).trigger('click');
});
}
function checkChildren() {
var selector = ".child-of-" + $(this).closest('tr').attr('id');
var isChecked = $(this).is(':checked') ? ':not(:checked)' : ':checked';
$(selector).find('input:checkbox' + isChecked).each(function () {
$(this).trigger('click');
$(this).change();
});
}
function toggleInputs() {
var isChecked = $(this).attr('checked');
var inputs = $(this).closest('tr').find('input:text');
if (isChecked)
inputs.removeAttr('disabled');
else
inputs.attr('disabled', 'disabled');
}
</script>
This is what my table looks like:
<table id="mappings">
<thead>
<tr>
<th><input type="checkbox" id="cb-master"></th>
<th>Title</th>
<th>Input</th>
</tr>
</thead>
<tbody>
<tr id="grandparent">
<td><input type="checkbox" id="cb-grandparent" /></td>
<td>Grandparent</td>
<td />
</tr>
<tr id="parent" class="child-of-grandparent">
<td><input type="checkbox" id="cb-parent" /></td>
<td>Parent</td>
<td />
</tr>
<tr id="child-1" class="child-of-parent">
<td><input type="checkbox" id="cb-child-1" /></td>
<td>Child 1</td>
<td><input type="text" /></td>
</tr>
<tr id="child-2" class="child-of-parent">
<td><input type="checkbox" id="cb-child-2" /></td>
<td>Child 2</td>
<td><input type="text" /></td>
</tr>
</tbody>
</table>
This works when I manually check/uncheck each box, but it does not work when I do it programatically through the toggleCheckAll() function. Is there something I have to do to bind this event programitically as well?
Also, I am having difficulty implementing the checkChildren function recursively, as every time I attempt to I get the exception nodeName is null or not an object.
Any input is greatly appreciated. Thanks.
Check out the jsfiddle
If instead of this:
try
To initially disable all input text, first do:
Does that answer your question? I wasn’t able to test it out, but I assumed that by actually triggering a click event it would execute the rest of the code or instead of binding it to a click event you would bind it to a change event, that should also work.