Pregunta

I've got a jQuery script that clones sortable rows of input fields. The script is configurable where you can insert the new cloned rows at the beginning (insertBefore) or at the end (insertAfter). Inserting new clones at the end is no problem and works as expected. But inserting at beginning poses a problem of the number sequencing.

Two examples:

  1. Say you have 4 rows saved in the database. When you clone the last row and insert it before the first row, the number is incremented to 5. But every clone after that is still cloning to 5 since the 4th row is still being used.

  2. Switch that to where you clone the first row and insert it before the first row... the incrementing starts at 2, 3 and so on, which would ultimately replace the previously saved rows upon saving.

Any ideas how I can get the insertBefore incrementing correctly? Could it be possible to reorder all the rows each time the clone click event is triggered? I'm not sure what type of solution could work here.

Here's the code I"m using for this:

$('.add-row').on('click', function(event) {
    function incrementProp(index, prop) {
        return prop.replace(/(\d+)/, function(fullMatch, n) {
            return Number(n) + 1;
        });
    }

    var clone_row,
        insert_location,
        clone_var = $(this).parents('.sortable');

    if (clone_var.is('.before')) {
        clone_row = clone_var.find('.sort-group .row:last');
        insert_location = clone_var.find('.sort-group .row:first');
        insert = 'insertBefore';
    } else {
        clone_row = clone_var.find('.sort-group .row:last');
        insert_location = clone_var.find('.sort-group .row:last');
        insert = 'insertAfter';
    }

    clone_row.clone(true)[insert](insert_location)
        .addClass('add').removeClass('first')
        .find('input[type=text], input[type=hidden], textarea, select').val('').attr('name', incrementProp).end()
        .find('input, textarea, select').attr('id', incrementProp);

    return false;
});

Any help that can be provided will be greatly appreciated!

Update: Added a basic fiddle of this. http://jsfiddle.net/85FY6/1/

¿Fue útil?

Solución

If you just need the id values to be unique and don't care if the order of id values matches the order of the rows, you could use the number of rows to get the next id value:

$('.add-row').on('click', function (event) {

    var newIndex = $('.sort-group').find('.row').length + 1;

    function incrementProp(index, prop) {
        return prop.replace(/(\d+)/, newIndex);
    }

    ...

jsfiddle

You might want to rename incrementProp() though since its name wouldn't fit anymore.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top