yesterday david shuck posted some jquery code he was using to toggle the display of some form information. one of the things i noticed about his code was that he was using jquery to bind to the change event of a radio button, but the code to acutally toggle the display was contained in a separate function.

i commented him back about how he could combine these two functions into one jquery chain thus making the code a little more readable. today i want to share this with you, let’s take a look at the two functions:

$("#RequireCCInfo").change(function(){
    toggleCreditCardCompanyPanel();
}); 	

function toggleCreditCardCompanyPanel()	{
    if ($("#RequireCCInfo").attr("checked") == true)
    $("#CreditCardCompanyPanel").show();
    else $("#CreditCardCompanyPanel").hide();
}

toggleCreditCardCompanyPanel();

basically the first function bind to the change event of a checkbox with an id of RequireCCInfo and then calls the toggleCreditCardCompanyPanel to toggle the display of the panel.

so how could chaining in jquery help us clean this up a little? remember that with jquery you can bind a function to an event and also trigger event. with this knowledge you can do things like:

$(function(){
$(“#RequireCCInfo”).bind(“change”, function(){
// your code
}).change();
});

as you can see from the code above, we’re binding some code to the change event and then immediately after triggering it, this is the same thing a creating a separate function and then calling it. armed with this knowledge we can now perform the clean up:

$(function(){
$(“#RequireCCInfo”).bind(“change”, function(){
$(“#RequireCCInfo:checked”) ? $(“#CreditCardCompanyPanel”).show() : (“#CreditCardCompanyPanel”).hide();
}).change();
});

Leave a Reply