2

I have a dynamic table on my page that a user can add rows/delete rows from. So let's say the user adds 6 people. The first name array would look like this:

Index:    0   1   2   3   4   5
Person#:  1   2   3   4   5   6

Then let's say the user deletes the first three rows, so the first name array would then look like this:

Index:    0   1   2   3   4   5
Person#:              4   5   6

Finally, the user adds three more people, the array would then be this:

Index:    0   1   2   3   4   5
Person#:              7   8   9

And this is the problem I am having. When deleting a row, how do I shift the jquery array appropriately so that instead of looking like this:

Index:    0   1   2   3   4   5
Person#:              4   5   6

It'll look like this:

Index:    0   1   2   3   4   5
Person#:  4   5   6   

Here's a working example of my code: demo
What do I need to add/change in my code to fix the problem?

4

3 回答 3

2

I normally simply renumber the attribute values. Something like this:

$("#table").find('tr').each(function(index, element)
{
    var row = $(this);

    index --;

    var names = ['fname_new', 'lname_new', 'phone_new', 'email_new', 'ethnicity_new'];
    for(var i in names)
    {
        row.find('input[name^="' + names[i] + '"]').attr('name', '' + names[i] + '[' + index + ']');
    }
});

http://jsbin.com/icutuj/3/edit

于 2012-10-01T22:12:55.647 回答
1

Rather than trying to fix the index what I do is create a hidden variable, let's call it Index, and every time a new row is added you Index++.

Then, when the data is posted back you can have something like this quick pseudo code:

for (int i = 0; i++ i<$index) {
   var person = $POST[person_$index];
   if (person != null) {
     //do something
   }
}

In this way you don't really care how many records they deleted.

Cheers!

于 2012-10-01T21:49:55.707 回答
1

Maybe not the best solution, but I got away with this by blanking the row values, then changing the delete() for hide(). and not maintaining a row count. hope theres a better solution.

    $('div#editPhoneDlg').delegate('a.remove[href^=#]', 'click', function () {

        var row = $(this).parent().parent();
        if (rowCount > 1) {
            var name = $(row).find('td.name input');
            name.val('');
            var address = $(row).find('td.address input');
            address.val('');
            var phone = $(row).find('td.phone input');
            phone.val('');
            row.hide();
        }
        else {
            var name = $(row).find('td.name input');
            name.val('');
            var address = $(row).find('td.address input');
            address.val('');
            var phone = $(row).find('td.phone input');
            phone.val('');
        }
        return false;
    });
于 2012-10-01T21:52:28.827 回答