SO - 21473767
HTML
<div id="main-panel">
<label>Item List</label>
<ul id="pq_entry_1" class="clonedSection">
<li style="list-style-type: none;">
<input id="first_item_1" class="main-item" name="main_item_1" type="checkbox"><label>First Item</label>
</li>
<ul class="sub-item" style="display: none;">
<li style="list-style-type: none;">
<input id="sub_item_1" name="sub_item_1" type="checkbox"><label>Sub Item</label>
</li>
</ul>
<li style="list-style-type: none;">
<input id="second_item_1" class="main-item" name="main_item_1" type="checkbox"><label>Second Item</label>
</li>
<ul class="sub-item" style='display: none;'>
<li style="list-style-type: none;">
<label>
How many items:
</label>
<select id="item_count_1" name="item_count_1" class="medium" required>
<option value="">---Select---</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</li>
<li style="list-style-type: none;">
<div id="item_names_1"></div>
</li>
</ul>
</ul>
<center><input type='button' class="button tiny radius" id='btnAdd' value='Add Another' />
<input type='button' class="button tiny radius alert" id='btnDel' value='Delete Last' /></center>
</div>
CSS
#main-panel li {
list-style-type: none;
}
JavaScript
$(document).ready(function () {
$('#main-panel').on('click', '.main-item', function () {
var $mainItem = $(this);
var $subItem = $mainItem.parent().next('.sub-item');
if ($mainItem.is(':checked')) {
$subItem.show();
} else {
$subItem.hide();
}
});
$('#btnAdd').click(function () {
var num = $('.clonedSection').length;
var newNum = num + 1;
var newSection = $('#pq_entry_' + num).clone().attr('id', 'pq_entry_' + newNum);
newSection.find('input[type="text"]').val('');
newSection.find('select').val('');
newSection.find('input[type="checkbox"]').prop('checked', false);
//hide sub item
newSection.find('.sub-item').hide();
//change the input element selectors to use name
newSection.find('input[name^="first_item_"]').attr('id', 'main_item_' + newNum).attr('name', 'main_item_' + newNum);
newSection.find('input[name^="second_item_"]').attr('id', 'second_item_' + newNum).attr('name', 'second_item_' + newNum);
newSection.find('input[name^="item_count_"]').attr('id', 'item_count_' + newNum).attr('name', 'item_count_' + newNum);
newSection.find('input[name^="sub_item_"]').attr('id', 'sub_item_' + newNum).attr('name', 'sub_item_' + newNum);
newSection.find('input[name^="other_item_"]').attr('id', 'other_item_' + newNum).attr('name', 'other_item_' + newNum);
newSection.insertAfter('#pq_entry_' + num).last();
$('#btnDel').click(function () {
var num = $('.clonedSection').length; // how many "duplicatable" input fields we currently have
$('#pq_entry_' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').prop('disabled', '');
// if only one element remains, disable the "remove" button
if (num - 1 == 1) $('#btnDel').prop('disabled', 'disabled');
});
});
$('#btnDel').prop('disabled', 'disabled');
...