С возможностью jquery я могу динамически добавлять или удалять поля флажков. У меня есть main checkbox
, который при нажатии будет показывать sub_item
. Чтобы добавить дополнительный флажок, как упоминалось ранее, я cloning
, а затем присваиваю новый флажок id
и name
. Но у меня есть два основных затруднения: если флажок main_item
будет установлен, он покажет его sub_item
, но когда я буду клонировать, я хотел бы показать main_item
sub_item
, как изначально скрытый? Во-вторых, неправильные значения id
и name
, назначенные новому sub_items
, присваивают значения тегам <li>
вместо этого флажка. JSFIDDLEДинамическое добавление и удаление полей ввода флажка
Jquery
$('#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 = new Number(num + 1);
var newSection = $('#pq_entry_' + num).clone().attr('id', 'pq_entry_' + newNum);
newSection.find('input[type="text"]').val('');
newSection.find('input[type="checkbox"]').prop('checked', false);
newSection.children(':first').children(':first').attr('id', 'main_item_' + newNum).attr('name', 'main_item_' + newNum).attr('placeholder', 'Item #' + newNum + ' Name');
newSection.children(':nth-child(2)').children(':first').attr('id', 'sub_item_' + newNum).attr('name', 'sub_item_' + newNum);
newSection.children(':nth-child(3)').children(':first').attr('id', 'other_item_' + newNum).attr('name', 'other_item_' + newNum);
newSection.insertAfter('#pq_entry_' + num).last();
$('#btnDel').prop('disabled', '');
if (newNum == 10) $('#btnAdd').prop('disabled', 'disabled');
});
$('#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');
HTML
<div id="main-panel">
<label>Item List</label>
<div>
<ul id="pq_entry_1" class="clonedSection">
<li style="list-style-type: none;">
<input id="main_item_1" class="main-item" name="main_item_1" type="checkbox"><label>Main 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>
<li style="list-style-type: none;">
<input id="other_item_1" name="other_item_1" type="checkbox"><label>Other Item</label>
</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>
</div>
первая проблема не ясна –