So here’s a quick on for all you boys and girls… and anything else I might have missed.
Say you want to check all check boxes in a grid or whatever, but you want it to toggle. So if if it’s time to check all, all get checked and then the next time the button is clicked it will uncheck. Now you could do this in three methods, maybe two but that’s why you’re a mouth breather.
Special people like me do it in one.
function toggleCheckboxes(buttonId, checkBoxNamePrefix, checked) { //Get all checkboxes with the prefix name and check/uncheck jQuery('[id*=' + checkBoxNamePrefix + ']').attr('checked', checked); //remove any click handlers from the button // Why? Because jQuery(buttonId).click() will just add another handler jQuery(buttonId).unbind('click'); //Add the new click handler jQuery(buttonId).click( function() { toggleCheckboxes(buttonId, checkBoxNamePrefix, !checked); } ); }
And POW! What? You want to know how to use it? Fine, but only because I’m nice.
jQuery('#buttonName').click( function() { toggleCheckboxes('#buttonName', 'someCheckBoxName', true); } );
And in case you were still wondering why I used .unbind and didn’t understand the comment, it’s because using just .click will add another handler to the button. So next click you will get both check and uncheck all. Kind of hurts the effectiveness.
And there you have it. Once again I have filled your life with meaning. Couldn’t be easier. Or maybe it could but that’s not my problem now is it? Go back to doing something useful.
Ha! You made me laugh. And I was, in fact breathing through my mouth at the time of reading. Although that was because I had a nasty cold.
Thanks for this. Very useful, and whimsnarkilicious, too. I’ll read more.
You have something against mouth breathers? Not that I am one, you know, just asking…