2014-01-31 2 views
0

С возможностью jquery я могу динамически добавлять или удалять поля флажков. У меня есть main checkbox, который при нажатии будет показывать sub_item. Чтобы добавить дополнительный флажок, как упоминалось ранее, я cloning, а затем присваиваю новый флажок id и name. Но у меня есть два основных затруднения: если флажок main_item будет установлен, он покажет его sub_item, но когда я буду клонировать, я хотел бы показать main_itemsub_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> 
+0

первая проблема не ясна –

ответ

2

Попробуйте

$('#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('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^="main_item_"]').attr('id', 'main_item_' + newNum).attr('name', 'main_item_' + newNum).attr('placeholder', 'Item #' + newNum + ' Name'); 
    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').prop('disabled', ''); 

    if (newNum == 10) $('#btnAdd').prop('disabled', 'disabled'); 
}); 

Демо: Fiddle

+0

T его то, что мне нужно было точно! Спасибо. – techAddict82

+2

Было бы проще и эффективнее обрабатывать ваше переименование в цикле, я обновил вашу скрипку: http://jsfiddle.net/5634e/1/ –

Смежные вопросы