tags:

views:

45

answers:

2

I have an element:

<select id="row" />

I want to append a string to the end of the id attribute, like this:

<select id="row_1" />

The jQuery I am using to achieve this is (from within an each):

$(this).attr('id',$(this).attr('id')+'_'+row_count);

This looks ugly as sin, and whilst it works I want to know if there is a simpler solution. In this example, the ID prefix (e.g. row) is never constant, so I can't just do 'row_'+row_count.

Cheers!

+3  A: 

You can pass .attr() a function, like this:

$("select").attr("id", function(i, val) {
  return val + '_' + i; //i == index, val == original attribute, the id
});

Scroll down a bit here to find the function overload for .attr()

Nick Craver
Many thanks for your response nick, much appreciated!
ILMV
@ILMV - Btw this would have the effect of `row_1`, `row_2`, etc if there was 1 select per row, otherwise just adjust the selector to only grab the ones you want to re-id and you can use `i` as the count.
Nick Craver
Cheers Nick, nickf's answer seems to have sorted me out. Thanks anyway :)
ILMV
+3  A: 

Don't forget that extending jQuery is super easy:

$.fn.appendAttr = function(attrName, suffix) {
    this.attr(attrName, function(i, orig) {
        return val + suffix;
    });
    return this;
};

And then everywhere else you want to do this:

$('p').appendAttr('id', 'i_like_turtles');
nickf
Would get a good speed boost with: `this.attr(attrName, function(i, val) { return val + suffix; });` if doing a large number of elements
Nick Craver
Nick, could you explain how this proveds a speed increase? Cheers! :)
ILMV
@ILMV - It's not accessing the attribute collection twice, it uses a reference to grab and set quickly.
Nick Craver
Thanks Nick, that was my original concern actually that it was accessing it twice. Many thanks :)
ILMV
@Nick, i don't know that accessing an attribute would cause a significant slowdown, but you're right: using the callback function is better, since the original code I posted wouldn't work for sets very well. I'll edit now.
nickf