Reputation: 1122
I'm a beginner in jQuery and here's what I'm trying to do:
Here's the code I made so far:
boxes = $('.chosen');
for(a = 0; a < boxes.length; a++) {
inputsinboxes = boxes[a].children('input');
for(b = 0; b < inputsinboxes.length; b++) {
inputsinboxes[b].name = inputsinboxes[b].name + (a+1);
}
}
I'm stuck though since it keeps telling me boxes[a].children
is not a function.
What am I doing wrong?
Upvotes: 2
Views: 115
Reputation: 359966
When you use array index notation (brackets) to access an element from a jQuery object, you don't get a jQuery object back. You get the underlying DOM node. http://api.jquery.com/get/
Start by using .each()
to make this more idiomatic jQuery:
$('.chosen').each(function (i) {
$(this).children('input').prop('name', function () {
return this.name + (i+1);
});
});
Upvotes: 3
Reputation: 6752
You're mixing raw javascript intuitions with how jquery operates. Try this on for size
$('.chosen').each(function(index) {
$('input', this).each(function() {
$(this).attr('name', $(this).attr('name') + (index + 1));
});
});
Upvotes: 3
Reputation: 75327
boxes[a]
is a DOMElement
, not a jQuery object; so you can't use the jQuery children()
method on it.
Instead you have to wrap it in a jQuery object first:
boxes = $('.chosen');
for(a = 0; a < boxes.length; a++) {
inputsinboxes = $(boxes[a]).children('input');
for(b = 0; b < inputsinboxes.length; b++) {
inputsinboxes[b].name = inputsinboxes[b].name + (a+1);
}
}
Also note that you should declare your variables with a var
to stop them being made implicit globals;
var boxes = $('.chosen');
Consider using the more common each()
function in jQuery rather than a for
loop. Coupled with the using prop()
as a setter and providing a function, you can shorten your code to just:
$('.chosen').each(function (i) {
$(this).children('input').prop('name', function (j, curr) {
return curr + (i+1);
});
});
Upvotes: 1