I'm trying to convince a supplier to adopt jQuery instead of using their own (awful) javascript library and so I'm knocking some examples based on the html pages they've already got.
One of the pages is your typical message list with a checkbox to select messages individually and a checkbox in the header to select them all, there's also delete and move buttons that get disabled based on the state of the checkboxes. I've knocked up the following example and it appears to work fine, but I wondered as it's my first crack at using jQuery if anyone could think of a nicer way of handling the code in the updateStates() method? $(document).ready(function(){ // Add event handler to checkbox in header to change the status of all check boxes when it's clicked. $(':[EMAIL PROTECTED]').click(function(){ var checked = this.checked; // Save the state of the checkbox in the header $(':[EMAIL PROTECTED]').each(function(i){ this.checked = checked; // Apply it to the others in the list }); updateStates(); }); // When a checkbox is checked or unckecked, change status of move and delete buttons, and checkbox in header $(':[EMAIL PROTECTED]').click(function(){ updateStates(); }); // Update the states of the buttons and the header checkbox when any of the others change function updateStates() { var allCheckboxes = $(':[EMAIL PROTECTED]'); // Create array of all checkboxes expect the header one var checkedCheckboxes = allCheckboxes.filter(':checked'); // Filter array to be just those that are checked if(allCheckboxes.length == checkedCheckboxes.length) { $(':[EMAIL PROTECTED]').attr('checked', 'checked'); // all boxes are checked, check header } else { $(':[EMAIL PROTECTED]').removeAttr('checked'); // not all boxes are checked, uncheck header } if(checkedCheckboxes.length == 0) { $('#btnMove').attr('disabled', 'disabled'); // No boxes are checked, disable buttons $('#btnDelete').attr('disabled', 'disabled'); } else { $('#btnMove').removeAttr('disabled'); // Some boxes are checked, enable buttons $('#btnDelete').removeAttr('disabled'); } } }); Cheers Andy