Ray S.
Ray S.

Reputation: 1200

jquery populate nested dynamic list

I think this is easy, but I'm beating my head up against a wall.

I have a nested dynamic list like this:

Volume 1
    Chapter 1
    Chapter 2
    +Add chapter
+Add volume

if one clicks on +Add volume, it should copy the minimum structure (only one chapter with button to add more) like this:

Volume 1
    Chapter 1
    Chapter 2
    +Add chapter
Volume 2
    Chapter 1
    +Add Chapter
+Add volume

is this hard to do in jquery?

right now I managed to do this only for a single level using a table.

    <table border="0" cellpadding="0" cellspacing="0" class="abstract" id="mbp_ray_main_table">
        </table>
    <input type="button" id="btn-add-row_mbp" value="+Add 1 Chapter">

the add chapter button is bound like this:
$( document ).ready(function() {
  $("#btn-add-row_mbp").click(function () {
    add_new_row_mbp();
  });
});
function add_new_row_mbp() {
  // When adding a row, bump the row count.
  $("#NumRows_mbp").val(++numrows_mbp);
  // And get a new rowid.
  newrowid_mbp++;
  var row_cnt_mbp = $('#mbp_ray_main_table tr').length + 1;

  var newrow_mbp='<tr id="rowid_mbp'+newrowid_mbp+'"><td>'
    +'<ul id="rowid_mbp'+newrowid_mbp+'">'
    +'<li>Chapter'+newrowid_mbp
    +'</li>'
    +'</ul></td>'
     +'</tr>';


  $("#mbp_ray_main_table").append(newrow_mbp);
}

Upvotes: 0

Views: 182

Answers (2)

Anton
Anton

Reputation: 32581

$('button').on('click', function () {
    var cnt = $('#test > li').length + 1;
    $('#test').append('<li>Volume ' + cnt + '<ul><li>Chapter1</li><li class="addChap">+ chapter</li></ul></li>');
});
$('#test').on('click', '.addChap', function () {
    var cnt = $(this).siblings().length + 1;
    $('<li>Chapter ' + cnt + '</li>').insertBefore(this);
});

DEMO

Upvotes: 1

RONE
RONE

Reputation: 5485

just a brief demo, can help you if you post your question in fiddle with nice html formatted structure.

//Considering your first "+Add volume" id is addvolume_1 $('#addvolume_1').on('click', function(){

    $(this).parent().after('
     <p>Volume 2</p>
     <p>Chapter 1<p>
     <p><a id='give some unique id'>+Add Chapter</a><p>');
    });

//When clicked on +Add Chapter
$('<some unique id>').on('click', function(){
...
});

Upvotes: 0

Related Questions