Reputation: 10828
I have created a template html block with allow me to copy that block when I click on Add button. This is done via append()
How to change the value of name='category[]'
input field after it has been appended?
For example:
$('#add').click(function() {
$('#LinesContainer').append($('#templatePlan').html());
var getCategory = $("#selectCategory").val();
// How to put getCategory value into category[] field?
});
Select Category and click on + button
<div>
<select id="selectCategory">
<option value="New">New</option>
<option value="Old">Old</option>
</select>
<input value="+" id="add" type="button"/>
</div>
Template Block
<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>
I am not sure if this is a neat way to implement it, is there alternative better way?
Upvotes: 0
Views: 2926
Reputation: 945
//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 + ']');
Upvotes: 0
Reputation: 664405
Just select it. I'd recommend to use .clone()
for the template instead of innerHTML
, that will make the selection easier. Otherwise you might have multiple category inputs and have to use that last one.
$('#add').click(function() {
$('#templatePlan').children('div').clone().appendTo('#LinesContainer')
.find('input name="category[]"').val($("#selectCategory").val());
});
Upvotes: 1