jQuery conditionals plugin 2007/08/22
jQuery provides a ton of ways to select sets of elements but pretty much no way to pare down a selection in an arbitrary way. Fortunately for me it's easy to extend jQuery, so I wrote a plugin that allows you to apply a function to your set of elements to pare the set down before applying an action. Source first, talk later:
jQuery.fn.if = function(arg) { var elems = []; var all = this.get(); var ii = all.length; for (var i = 0; i < ii; ++i) { if (arg.apply(all[i])) { elems.push(all[i]); } } return jQuery(elems); };
jquery.if.js (version 0.1)
The plugin takes as its argument a function that must return a boolean value. This function will be applied to every argument in the current set. Those that the function finds true will be returned in the final subset.
The use-case that inspired this quickie plugin is this: I wanted an action to happen to form fields that were empty, which previously required a bit of work. If I had more work to do with each match or a more complex matching requirement, this could get ugly.
$('input.promptable').focus(function() { var to = $(this); if ('' == to.val()) { to.val(this.id); to.addClass('prompt'); } });
With this plugin, the chaining action jQuery is known for is not interrupted. I can select all input
elements with the promptable
class and pare down that selection to only those whose value is empty. On the set returned there I can set values and add classes without breaking the chain.
$('input.promptable').focus(function() { $(this).if(function() { return '' == $(this).val(); }).val(this.id).addClass('prompt'); });
jquery.if.js (version 0.1)
Comments (2)
Hey Richard,
Just wanted to let you know that the functionality you are looking for is built into the .filter() method. Filter can take either a selector or a function. Those jQuery core methods can be hard to find sometimes and it is just so easy to quickly write a plugin for what you need. :) Anyways, here are the docs for the filter method: http://jquery.bassistance.de/api-browser/#filterFunction http://jquery.bassistance.de/api-browser/#filterString
— Brandon Aaron — 2007/08/22 10:42 am
D'oh! You're right, they're sometimes quite hard to find and I never would have called it "filter". Thanks for the tip, Brandon.
— Richard Crowley — 2007/08/22 10:48 am