tags:

views:

28

answers:

2

Let's say I have following jQuery line where I am trying to change the "id" of the element after cloning the row of a table. How can I refer to the instance of the element and pass it to "buildControlId" function.

$row.find("select [id$='ctlType']").attr("id", buildControlId(???));

I could do it like this, but I am looking for shorter version without needing to declare variable.

var $el = $row.find("select [id$='ctlType']");
$el.attr("id", buildControlId($el[0]));
+1  A: 
$row.find("select [id$='ctlType']").each(function() {
   $(this).attr("id", buildControlId(this));
});

This way also has the advantage of working on multiple elements. Consider changing your selector to select multiple elements (if that makes sense).

noah
+1  A: 

You can specify a function as the second parameter:

$row.find("select [id$='ctlType']").attr("id", function(){
    buildControlId($(this));
});

And your function would return the value for the attribute:

function buildControlId($param){
    return "hello";
}
James Wiseman
Ahh so if I use function then "this" gives me the element. I was trying without function, just using this, but that was giving me element to which 'click' event was bound too.
epitka
Yeah, `this` is dead useful in that respect. You'll notice that @noah did this same in his `each()` answer
James Wiseman