2013-08-05 93 views
0

我創建了一個模板html塊,允許我在單擊「添加」按鈕時複製該塊。這是通過append()在append()後更改輸入值()

如何更改name='category[]'輸入字段的值後,它已被附加?

例如:

$('#add').click(function() { 
    $('#LinesContainer').append($('#templatePlan').html()); 
    var getCategory = $("#selectCategory").val(); 
    // How to put getCategory value into category[] field? 
}); 

選擇類別,點擊+按鈕

<div> 
    <select id="selectCategory"> 
     <option value="New">New</option> 
     <option value="Old">Old</option> 
    </select> 
    <input value="+" id="add" type="button"/> 
</div> 

模板塊

<div id="templatePlan" style="display:none;"> 
<div style='padding: 5px; border: 1px solid white; background-color: #FFA86F;'> 
    <select name="selectType[]"> 
     <option>Consumer</option> 
     <option>Business</option> 
    </select> 
    <input name='category[]' type='hidden' value='' /> 
</div> 
</div> 


<div id="LinesContainer"> </div> 

我不知道這是否是實現它一個整潔的方式有沒有其他更好的方法?

回答

1

只要選擇它。我建議使用.clone()作爲模板而不是innerHTML,這將使選擇更容易。否則,您可能會有多個類別輸入,必須使用最後一個輸入。

$('#add').click(function() { 
    $('#templatePlan').children('div').clone().appendTo('#LinesContainer') 
    .find('input name="category[]"').val($("#selectCategory").val()); 
}); 
+0

謝謝!您如何看待整體實施設計?或者每個附加的塊應該像索引號一樣?所以每次點擊Add按鈕,它都會得到最大的索引並增加1。例如:'category_5'字段名稱 –

+0

那麼,數組很好。 jQuery並不優雅地處理它們,但它比不必要的ID更好。只有一個改進:將隱藏的模板div與其子div合併,然後使用'$('#templatePlan')。clone()。show()...' – Bergi

+0

嗯,我想弄清楚。當我點擊一個提交按鈕,如果有錯誤 - 它會返回到表單頁面,但我需要重新填充字段數據的附加塊。如何做到這一點?我正在使用PHP。 –

0
//after 
    var getCategory = $("#selectCategory").val(); 

//To set the actual input 
    $('input[type="hidden"]').val(getCategory); 
//or to update the attribute rather 
$('input[type="hidden"]').attr('name', 'category[' + getCategory + ']');