简体   繁体   中英

JS/jQuery number increasing in for

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 is name[0][], name[1][] .
in "field 2" put number 3 we get name[0][], name[1][], name[2][]
in "field 3" put number 2 we get name[0][], name[1][]

I want thie:

if put to "field 1" number 2 we get tow new input that name it is name[0][], name[1][]
in "field 2" put number 3 we get name[2][], name[3][], name[4][]
in "field 3" put number 2 we get name[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+'][]">');        
    }
});

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM