1

次のような HTML があります。

<div id='main'>

   <div id='child-0'>
     <input type='text' name='data[0][name]'>
     <input type='text' name='data[0][dob]'>
     <input type='text' name='data[0][location]'>
   </div>

</div>

<input type='button' id='add' value='Add'>

jQuery:

$("input#add").live( 'click', function(){
   $("#main").append("<br />");
   $("#child-0").clone(false).appendTo( $("#main") );
});

上記のコードは機能していますが、同じ名前の要素を作成しています。私はそれを次のように生成したい:

<div id='main'>

   <div id='child-0'>
     <input type='text' name='data[0][name]'>
     <input type='text' name='data[0][dob]'>
     <input type='text' name='data[0][location]'>
   </div>

   <div id='child-1'>
     <input type='text' name='data[1][name]'>
     <input type='text' name='data[1][dob]'>
     <input type='text' name='data[1][location]'>
   </div>

</div>

簡単な解決策は何ですか。

ありがとう

4

1 に答える 1

2
$("input#add").live( 'click', function(){
    $("#main").append("<br />");
    var cloned = $("#main div:last").clone(false).appendTo( $("#main") );
    cloned.find('[name^=data]').attr('name', function() {
        var index = this.name.match(/\[(\d)\]/);
        if (index != null && index.length > 1) {
            var newIndex = parseInt(index[1], 10) + 1; 
            return this.name.replace(/\[(\d)\]/, '[' + newIndex + ']');
        }
        return this.name;    
    });
});​
于 2012-05-29T14:08:35.770 に答える