Update the inline of an html table

Asked

Viewed 473 times

2

How do I update the line index of an html table after removing it ? I explain better I have a table 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 remove table item:

 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 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 model is populated so:

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

I need him to stay that way:

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

1 answer

1


Set a single class for the rows containing 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 scroll through each row of the table that contains the class you defined, looking for the fields by id and setting the name property using a counter. With each removal you make, the counter is reset and each field will have the value rearranged, always leaving in the correct order.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.