2017-01-30 76 views
1

我有問題,當我試圖複製一組字段。如何克隆新的字段組,並增加名稱屬性

,比如我有

<div class="must_Duplicated "> 
<div class="form-group"> 
    <label >Name:</label> 
    <input type="text" class="form-control" name="study[0].name" > 
</div> 
<div class="form-group"> 
    <label>Middle:</label> 
    <input type="text" class="form-control" name="study[0].Middle" > 
</div> 
    <div class="form-group"> 
    <label>Surname:</label> 
    <input type="text" class="form-control" name="study[0].surname" > 
</div> 
</div> 

我需要的是複製 'must_Duplicated' 上課的時候我的東西

單擊但這個想法是遞增

study[0].name 
study[0].Middle 
study[0].surname 

study[1].name 
study[1].Middle 
study[1].surname 

我已經嘗試了很多辦法,但我無法找到一個解決方案來增加每次在名稱的值

高於自己僅僅是一個例子我的代碼比這更長

+0

我不認爲你可以像自動遞增,陣列這樣的事情沒有編程語言。 –

+0

我可以在angularjs中做到這一點,但我不需要去角內只有一件事 – programmer

+0

我認爲你想要1而不是1,2,3所有索引顯示 – rahulsm

回答

0
$("button").click(function(e){ 

    var mdCopy = $('.must_Duplicated').clone(); 

    $.each($(mdCopy).find('input'), function(){ 
    var n = parseInt($(this).attr('name').match(/\d/g), 10); 
    var startString = $(this).attr('name').split("[")[0]; 
    var endString = $(this).attr('name').split(".")[1]; 

    //increment the number 
    n++; 

    //rebuild the string 
    $(this).attr('name', startString + "[" + n + "]." + endString); 

    }); 

    //md_Copy now has updated inputs 
    console.log(mdCopy); 

}); 

這將打破串起來,增加數量,然後把它重新放回原來的DIV的副本 - 雖然這給人的格式

研究[1]。名稱

研究[1] .Middle

研究[1] .surname

,而不是在問題的1,2,3格式。希望這有助於

+0

嗨,謝謝你我會嘗試你的解決方案。 我想我犯了一個錯誤,當我寫1 2 3上面 ,因爲它的1 1 1 – programmer

0

本地JavaScript:

function duplicateForm() { 
    // get a copy of the first form which is as good as any. 
    var all_instances = document.getElementsByClassName("duplicate"); 
    var first_instance = all_instances[0]; 
    var clone_instance = first_instance.cloneNode(true); 

    // calculate the new index (just the number of existing instances of the form) 
    var new_index = all_instances.length; 

    // increment index of the study "array" 
    var new_inputs = clone_instance.getElementsByClassName("form-control"); 
    for (var i = 0; i < new_inputs.length; i++) { 
    new_inputs[i].name = new_inputs[i].name.replace(/\[\d+\]/, "[" + new_index + "]"); 
    } 

    // put new instance where you want it 
    document.body.appendChild(clone_instance); 
} 

https://jsfiddle.net/rur36n4x/17/