jQuery Plugin To Return Delimited Value List Of Stack Element Attributes

Posted July 11, 2007 at 3:07 PM by Ben Nadel

Tags: Javascript / DHTML

I was trying to give Tony Petruzzi some feedback on his record sorting algorithm when I mentioned that with jQuery it would probably be quite easy to get a comma-delimited list of database IDs for use with the sort update. I assumed that there would be something already built into the jQuery API for doing this; however, with a quick look at the API, it looks like all the attribute-getting methods (attr()) work on the first item in the jQuery stack, not the set of elements.

I am sure that this ability is already part of the vast API (that I am just not seeing) or at least it is already covered by an existing plugin, but I thought this would be a perfect time for me to exercise some of my jQuery plugin writing skills. Below, I wrote a jQuery plugin called attrList(). This returns a delimited list of a given attribute for all elements in the current jQuery stack. You can also pass in an optional second argument, the delimiter, which is defaulting to comma.

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • <html>
  • <head>
  • <title>Writing jQuery Plugin Demo</title>
  •  
  • <!-- Linked Files. -->
  • <script type="text/javascript" src="jquery.pack.js"></script>
  • <script type="text/javascript">
  •  
  • // This jQuery v1.1.3 plugin will return an delimited
  • // list of the given attribute of all elements in the
  • // current jQuery stack.
  •  
  • jQuery.fn.attrList = function( strAttribute, strDelimiter ){
  • // Start out with an empty value list. This list
  • // will eventually contain a delimited list of
  • // each attribute value.
  • var strValueList = "";
  •  
  • // Check to see if we were given a delimiter.
  • // By default, we will use the comma.
  • strDelimiter = (strDelimiter ? strDelimiter : ",");
  •  
  • // Loop over each element in the jQuery stack and
  • // add the given attribute value to the list.
  • this.each(
  • function( intI ){
  • // Get a jQuery version of the current
  • // stack element.
  • var jNode = $( this );
  •  
  • // Add the attribute to the list. When
  • // adding the value, check to see if
  • // we need to add the leading delimiter.
  • strValueList += (
  • (strValueList.length ? strDelimiter : "") +
  • jNode.attr( strAttribute )
  • );
  •  
  • }
  • );
  •  
  • // Return the value list.
  • return( strValueList );
  • }
  •  
  •  
  • // This will return the ID list of all inputs
  • // with the name, "ID".
  •  
  • function GetIDs(){
  • return(
  • $( "input[@name='id']" ).attrList( "value" )
  • );
  • }
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <form>
  •  
  • <!---
  • Get some hidden values. The order of the
  • value is important. We want to make sure
  • this is reflected in the value list.
  • --->
  • <input type="hidden" name="id" value="4" />
  • <input type="hidden" name="id" value="5" />
  • <input type="hidden" name="id" value="1" />
  • <input type="hidden" name="id" value="2" />
  • <input type="hidden" name="id" value="3" />
  •  
  • <input
  • type="button"
  • value="Alert Value List"
  • onclick="alert( GetIDs() );"
  • />
  •  
  • </form>
  •  
  • </body>
  • </html>

Normally, the jQuery plugin code would be written to a separate Javascript file, but for demo purposes, I have just put it in the HEAD of the HTML page. If you were to click on the input button, the page would alert the following text:

4,5,1,2,3

This is the comma delimited list of the Value attribute of all input fields with the name "id". Look how freakin' easy jQuery makes things like this:

  • $( "input[@name='id']" ).attrList( "value" )

As you can see in the code, the alerted value is reflective of the order that the hidden input fields appear in the document. This works because jQuery collects elements in its stack based on a top-down search. Meaning, elements that it finds earlier in the document are added to the stack first. Man, I love jQuery and I really finding it fun to write jQuery plugins.

Also, on a side note, this was run using the new and ultra fast jQuery v1.1.3. Good stuff!




Reader Comments

Jul 11, 2007 at 6:21 PM // reply »
95 Comments

Neato, thanks for posting this. I'm still using prototype.js but jQuery seems pretty damn nice.


Jul 11, 2007 at 6:21 PM // reply »
56 Comments

Ben,

Thank you for all your help today. :)


Jul 12, 2007 at 7:17 AM // reply »
11,238 Comments

Hey guys, I just realized there is a big mistake in the above code. Once inside of a jQuery plugin, you are not supposed to refer to the "$" object any more (as jQuery might release it back to be compatible with existing code). Instead, in the above, all the "$" should be replaced with the "jQuery" variable reference.


Jul 12, 2007 at 12:17 PM // reply »
170 Comments

@Ben:

I'd recommend using arrays instead of strings. If the attribute value would contain a comma, the list will be wrong.

Even if you prefer to return a string instead of an array, use an array and then use the join() method. This is much more efficient than concatenating a string together. The performance won't be noticable in with a small dataset like in your example, but it's really noticeable when you string size grows.


Jul 12, 2007 at 12:23 PM // reply »
11,238 Comments

@Dan,

Good point. And, in fact, after I wrote this, someone pointed out to me a similar algorithm that mapped jQuery stack elements to an array of values and then joined the array at the end.

It's really cool how flexible jQuery is.


Jul 30, 2011 at 2:05 PM // reply »
1 Comments

I just stumbled about the map-function (http://api.jquery.com/map/), which can do pretty much the same. I've not tested it, but this should work as an example:

var valueList = $('input[@name='id']').map(function() { return $(this).attr('id'); }).get().join(',');

best,
/m


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 21, 2013 at 7:46 PM
Using Plupload For Drag & Drop File Uploads In ColdFusion
No luck. At least I have uncovered the cause, URLScan 3.1. Here is what I see in the IIS log when a file is over 30mb. 2013-05-21 23:29:05 10.105.45.128 GET /plupload/assets/jquery/jquery-1.8. ... read »
May 21, 2013 at 6:12 PM
Using Plupload For Drag & Drop File Uploads In ColdFusion
Ben, I did not see you after Pete Freitag's Lockdown session at cfObjective but he said that IIS sets file size limits at 30MB by default which just happened to be the threshold for file size when ... read »
May 21, 2013 at 11:51 AM
Ask Ben: Parsing Very Large XML Documents In ColdFusion
Looking at my first ever XML document that I have to parse and put into MS SQL 2000 with CF8. I get it to list the desired Field name, many times over, and have a long list of this field name displa ... read »
May 21, 2013 at 9:25 AM
Turning Off and On Identity Column in SQL Server
you are awesome..i am lucky to get this blog between such a garbage one....Thanks, Prashant ... read »
May 20, 2013 at 4:38 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
@Dana, Your confusion is well founded, since this is a very confusing features. In fact, it ONLY works if you use array notation. Meaning, that this: arrayToList( query[ "columnName" ] ) ... read »
May 20, 2013 at 4:34 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
I was thinking chicken and the egg, I wouldn't have expected it to work in the valuelist going in I guess. Maybe I just need a beer, long day :) ... read »
May 20, 2013 at 4:29 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
@Dana, That's if you're trying to reference a specific row. In this case, we're trying to reference the entire query column as one cohesive value. So, you are correct that if you wanted to output a ... read »
May 20, 2013 at 4:24 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
I thought when you used array notation to reference queries you always had to have the row or it would throw a similar error as well? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools