jqueryjquery-clone

Duplicate table row opn edit page


I am facing a little problem. I have a table where I can add and remove table rows. I do this by basically cloning a template row e.g.

var $tr = $template.clone().removeClass('template').prop('id', tr_id);

I have a FIDDLE which show this working perfectly.

So I thought all was well, but I am working in Laravel and once the page is saved I display an edit page. The edit page prepopulates the table to the point it was at. So if I added two rows and saved, the edit page would be on the third row.

I have set up a second FIDDLE to try and demonstrate my problem. As you can see, this time if you delete the rows that are there you can no longer add a new row because it ask you to add data. This occurs even if you add the data.

I am trying to figure out why this is happening but having no joy? How could I get this working properly on the edit page?

Thanks


Solution

  • Your .tempate row is the last one in the table and hidden after you remove a row. You can't add until you fill it. Your selector should ignore it.

    The problem is your template is in the table, invisible, but not being ignored and the selector checks if that template is filled before adding a new row.

    Changing your add logic to the following will resolve this issue:

    $('#add').on('click', function() {
            $last_row = $('#table1 > tbody  > tr:not(.template)').last();
            if(!hasValues($last_row)){
                alert('You need to insert at least one value in last row before adding');
            } else {
                add_row($('#table1'));
            }
        });
    

    Alternately I would personally put any templates in a separate section.

    Update You need to initialize the datepicker for existing rows as well when you load the pre-populated table by adding the following on the beginning of your ready function:

    $("#table1 .hasDatepicker").removeClass("hasDatepicker");
       $("#table1 tr:not(.template)").find('.dateControl').each(function() {
                $(this).datepicker({
                dateFormat: "dd-mm-yy"          
            });
        });
    

    Updated fiddle https://jsfiddle.net/cLssk6bv/5/