Monday, December 15, 2008

jQuery appendToArray plugin

With jQuery, I found no real way of grouping elements together (other than using a class, and using filter), so I thought about adding jQuery objects to an array (or multiple arrays), which can then be iterated over with jQuery.each. I tried appendTo (on the off chance that it would work with plain arrays), but no such luck. So I created a simple plugin:

jQuery.fn.appendToArray = function()
{
 var a = arguments;
 for(var i = 0; i < arguments.length; i++) a[i][a[i].length] = this;
 return this;
}

Through using arguments, it can be appending to multiple arrays at the same time:

var ar1 = [];
var ar2 = [];
var $field1 = $("[name='field1']").appendToArray(ar1, ar2);
var $field2 = $("[name='field2']").appendToArray(ar1);
var $field3 = $("[name='field3']").appendToArray(ar1, ar2);
var $field4 = $("[name='field4']").appendToArray(ar2);
var $field5 = $("[name='field5']").appendToArray(ar2);

You can then loop through the arrays, with specific functions applied:

$.each(ar1, function()
 {
  console.log(this.attr("name") + " is in ar1");
 }
);

$.each(ar2, function()
 {
  console.log(this.attr("name") + " is in ar2");
 }
);

No comments: