0

I need to pass a list, based of of user input, from my view to the controller. I created a table using javascript, using a hidden input in each row incrementing the index in the id and name attributes as the user adds to the list. The issue is, I can not figure out how to decrement the index of each id and name if the user chooses to remove an element. I don't know much javascript... I hope you can understend my explanation.

This is my table.

    <table id="cat-table" class="table table-responsive">
        <thead>
            <tr>
                <th>Num Control</th>
                <th>Usuario</th>
                <th></th>
            </tr>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>

This is how I print each row.

 $("#tbody").append("<tr  id='filaUsuario" + usuario.id + "' ><td><input name='Usuario[" + i + "].UsuarioId' type='hidden' id='Usuario[" + i + "].UsuarioId' type='hidden'  value='" + usuario.id + "' />" + usuario.id + "</td><td>" + usuario.name + "</td><td> <button type='button' class='btn btn-default' name = 'btn-Quitar' id = 'btn-Quitar' onclick= eliminar('" + i + "','"+ usuario.id +"') value='" + i + "'>Quitar</button></td></tr>");

And this is how I try to decrement the remaining elements

     function eliminar(valor, usuario) {
        //$("#filaUsuario" + usuario).remove();

        $("#tbody tr").find("td:first").find("input").removeAttr("id");
        $("#tbody tr").find("td:first").find("input").attr("id", "Usuario['"+ 
      --i +"'].UsuarioId");

     }
  • Why do you have to change the id? How do you know which user input is which when the id changes every time? Why not just keep all the list items in an array and set the new id to the array length? Then you can keep all the id's the same and removing a row becomes trivial. – Shilly Aug 02 '18 at 14:16
  • The `id` is irrelevant and should be removed. If you are wanting to dynamically add and remove items, refer [Submit same Partial View called multiple times data to controller?](https://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) (and for a detailed implementation using `BeginCollectionItem`, refer [A Partial View passing a collection using the Html.BeginCollectionItem helper](https://stackoverflow.com/questions/40539321/a-partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892)) –  Aug 02 '18 at 23:29

0 Answers0