Reputation: 266
I need to replace a number of name and id attributes on cloned html elements and wrote a simple replace function that replaces all the numbers in the attribute strings.
I use .find to find an element in a div and then use .attr() to replace the name or id but I want to use the found element as $(this) or anything else.
So how can I target the element that I found by calling .find()?
This is what I want to use or something similar
newField.find('input[type="hidden"]').attr('name', replaceNumbersinStringTo($(this).attr('name'), index+1));
The problem lies in the $(this) that doesnt contain in this case the hidden input.
Replace function
function replaceNumbersinStringTo(string, replaceTo)
{
return string.replace(/\d+/g,replaceTo);
}
Upvotes: 0
Views: 44
Reputation: 9275
newField.find('input[type="hidden"]').each(function(i){
$(this).attr('name', replaceNumbersinStringTo($(this).attr('name'), i+1);
});
I'm not sure how you use "index" or i in my example, so that might need to be modified a bit to fit your needs.
Alternatively I would say consider using a template and rendering elements that way if you are going to be doing this cloning operation a lot. You could essentially put tokens into your template where the name attribute goes, and then just pass the appropriate value in when you render the template. Examples here: http://handlebarsjs.com/
Upvotes: 1
Reputation: 388316
The problem is the use of this
. this
inside the function call refers to the context of the function where the code is present not the newField
element.
newField.find('input[type="hidden"]').attr('name', function (i, name) {
return replaceNumbersinStringTo(name, index + 1)
});
or
newField.find('input[type="hidden"]').attr('name', replaceNumbersinStringTo(newField.attr('name'), index+1));
Upvotes: 1
Reputation: 17340
The easiest way to solve this is to declare your found element in a variable.
var found = newField.find('input[type="hidden"]');
found.attr('name', replaceNumbersinStringTo(found.attr('name'), index+1));
This essentially replaces your $(this)
function, which also means you can do more things on your found object without asking jQuery to create and return a new jQuery object.
Upvotes: 1