Update the index of the row of a table html

2

How do I update the row index of a table html after removing it? I better explain I have a table that I can add or delete items to add I use an auto increment variable: _contaLinha++ :

Add items to the table:

function Adicionar() {            
    if ($("#select_laudoexameid").val() > 0) { 
        $(".tblCadastro tbody").append(
            "<tr>" +
            "<td><input type='text' name='Laudo[" + _contaLinha + "].ExameID'  id='Laudo_ExameID' Value='" + $(".ExameID").val() + "' style='width:100%;border:none;' readonly='true'; class='tblCadastro_exameid'/></td>" +
            "<td><input type='text' name='Laudo[" + _contaLinha + "].TipoExameID'  id='Laudo_TipoExameID' Value='" + $("#select_laudoexameid option:selected").val() + "' class='tblCadastro_tipoexameid'/></td>" +
            "<td><input type='text' name='ListLaudo[" + _contaLinha + "].Nome'  id='ListLaudo_Nome' Value='" + $("#select_exameid option:selected").text() + "' class='tblCadastro_nome'/></td>" +
            "<td><img src='/Content/Images/excluirFlatRed.png' class='btnExcluir' title='Excluir' class='tblLaudoTipoExame_btnexcluir'/> </td>" +
        "</tr>");
        _contaLinha++;
        $(".btnExcluir").bind("click", Excluir);
    };
};

Here I pull item from the table:

 function Excluir() {                      
    var par = $(this).parent().parent();
    par.remove();
};

When I do the postback I send a list with 4 items like this:

Laudo[0].nome
Laudo[1].nome
Laudo[2].nome
Laudo[3].nome

The problem is when I remove an item from the list, example I remove the first item:

Laudo[0].nome //<-----Retiro esse item
Laudo[1].nome
Laudo[2].nome
Laudo[3].nome

The model (report model) should be populated with 3 items, but the msmo returns Null, if I remove item 3, example:

Laudo[0].nome
Laudo[1].nome
Laudo[2].nome <-----Retiro esse item
Laudo[3].nome

The template is populated like this:

Laudo[0].nome
Laudo[1].nome
Laudo[3].nome

I need it to look like this:

Laudo[0].nome
Laudo[1].nome
Laudo[2].nome
    
asked by anonymous 04.05.2016 / 00:30

1 answer

1

Define a single class for the rows that contain the data. After that, after removing the item, you can do this:

    var contador = 0;
    $( ".classeDaLinha" ).each(function() {
        $(this).find("#Laudo_ExameID").prop("name", "Laudo["+contador+"].ExameID");
        $(this).find("#Laudo_TipoExameID").prop("name", "Laudo["+contador+"].TipoExameID");
        $(this).find("#ListLaudo_Nome").prop("name", "ListLaudo["+contador+"].Nome");
        contador++;
    });

What this does is to traverse each row of the table that contains the class you defined by looking up the fields by the id and setting the name property using a counter. With each removal you make, the counter is restarted and each field will have the value rearranged, always leaving it in the correct order.

    
04.05.2016 / 16:48