Reputation: 2277
According to the example, i want in each times adding new input with putting number in fields(1, 2, 3), number increasing in each one from new input adding to name[+number increasing here+][]
in the input.
Now i have this in my code:
Example:
if put to "field 1" number
2
we get tow new input that name it isname[0][], name[1][]
.
in "field 2" put number3
we getname[0][], name[1][], name[2][]
in "field 3" put number2
we getname[0][], name[1][]
I want thie:
if put to "field 1" number
2
we get tow new input that name it isname[0][], name[1][]
in "field 2" put number3
we getname[2][], name[3][], name[4][]
in "field 3" put number2
we getname[5][], name[6][]
and etc.
Code:
$('input').live("keyup", function () {
var id = '#'+$(this).closest('b').attr('id');
$(id+' .lee').empty();
var $val = $(this).val();
for (var i = 0; i < $val; i++) {
$(id+' .lee').append('<input type="text" name="hi['+i+'][]">');
}
});
Upvotes: 0
Views: 349
Reputation: 11889
By using a variable outside the function, you can solve this simply. However, it would always just increment the index numbers; if you typed the counts in in the wrong order, your indexes would be in the wrong order. But maybe that's okay.
var counter = 0;
$('input').live("keyup", function () {
var id = '#'+$(this).closest('b').attr('id');
$(id+' .lee').empty();
var val = int($(this).val());
for (var i = counter; i < val + counter; i++) {
$(id+' .lee').append('<input type="text" name="hi['+i+'][]">');
}
counter = val + counter;
});
EDIT: fixed val coming through as a string not an int
Upvotes: 0
Reputation: 5024
Since you want to update all of the inputs on change, you could loop through all inputs after appending the elements. Just add a classname to them so you know which ones to count.
Example:
$('input').live("keyup", function () {
var id = '#'+$(this).closest('b').attr('id'),
val = $(this).val();
$(id+' .lee').empty();
for (var i = 0; i < val; i++) {
$(id+' .lee').append('<input type="text" class="input_generated">');
}
$('input.input_generated').each(function(i) {
$(this).attr('name', 'hi[' + i + '][]');
});
});
Fiddle: http://jsfiddle.net/rHUqS/1/
Upvotes: 2