2013-08-05 91 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 + ']');