开发者

How to automatically generate input-array index in jQuery?

开发者 https://www.devze.com 2023-03-17 14:00 出处:网络
For example, I have such HTML: <input name=\"someinput[]\"> I made a function to clone/remove this input but now I want to assign indexes to name dynamically - when I make an element clones,

For example, I have such HTML:

<input name="someinput[]">

I made a function to clone/remove this input but now I want to assign indexes to name dynamically - when I make an element clones, its new names should be someinput[1], someinput[2] etc. - 开发者_运维技巧how to make this?


You could just replace [] with [index] using the attr callback:

var i = 0;
$('button').click(function(){
 $('input:first').clone().attr('name',function(a,e){    
    i++;
    return e.replace("[]","["+i+"]");
 }).insertAfter($('input:last'));
});

example: http://jsfiddle.net/niklasvh/c9G7c/


Keep the index of the next input in a global variable, and then use that in your cloning function. Is that what you do?

var source = $('#source')
var copy = source.clone().attr('name', 'some[' + index + ']')
$('body').append(copy);
0

精彩评论

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