Sunday, October 28, 2012

jQuery filter, promotes DRY principle

You have this:

<input type='radio' name='TravelToCountryId' value='PH'> Philippines
<input type='radio' name='TravelToCountryId' value='CA'> Canada
<input type='radio' name='TravelToCountryId' value='ZH'> China​​​​​​​​


var country = $('input[name=TravelToCountryId]');
$(country).change(function() {     

You want to set the default(say Canada) using this:


Though that works, but as an astute developer you are, you feel that you are violating DRY principle and noticed that you can re-use the country object.

To re-use, use filter function. filter and find functions are almost synonym, however don't confuse them, find is for getting the descendant elements of existing elements, filter is for getting the elements from existing elements based on filter.

Do this:


No comments:

Post a Comment