开发者

Problem in for-loop for add new input with a number increasing

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.

Example: this exampl开发者_StackOverflow中文版e not worked true

I want this:

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(how is, fixed val coming through as a string not an int!?):

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: I re-read your question and believe I have a solution that has your desired behavior:

The JavaScript:

var counter = 0;
$('input').live('keyup', function(e) {
    // bail out if the keypress wasn't a number
    if (e.which < 48 || e.which > 57) { return; }

    // get the current value of the input
    var val = +$(this).val();

    // don't do anything if we don't have a valid number
    if (isNaN(val)) { return; }

    // find and empty .lee
    var $lee = $(this).closest('b').find('.lee').empty();

    // create inputs
    for (var i = 0; i < val; i++) {
        $('<input type="text"/>').attr('name', 'hi[' + (counter + i) + '][]')
            .appendTo($lee);
    }

    // update our counter
    counter = val + counter;
});

Here's the updated jsFiddle: http://jsfiddle.net/wAwyR/14/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜