delete tr from a table and keep the order of the IDs

2

I wanted to know if there is a way to delete a row from a table using jquery where the ids are ordered correlatively keeping the order. This is, for example:

<tr id=1>
<tr id=2>
<tr id=3>

If I delete row 2 it should look like this:

<tr id=1>
<tr id=2>

That's it, any help is welcome.

The following code goes through the options of a multiselect leaving the selected option to the last one and then deletes it. At the end delete the row from the table, but it happens the ids of the table lose their correlativity.

function eliminar(t)
{
    var len = document.getElementById("detalle").length;//multiselect
    var i=t;

     if (i >= 0){

        for (var j=i;j<len;j++){
            var paso_text = document.getElementById("detalle").options[j].text;
            var paso_value = document.getElementById("detalle").options[j].value;

            document.getElementById("detalle").options[j].text =  document.getElementById("detalle").options[j+1].text;
            document.getElementById("detalle").options[j].value =  document.getElementById("detalle").options[j+1].value;
            document.getElementById("detalle").options[j+1].text =  paso_text;
            document.getElementById("detalle").options[j+1].value =  paso_value;
        }
        document.getElementById("detalle").length = len-1;    
    }else{
        alert("!! Seleccione el producto a quitar !!");
    }

    $('#tabla_resumen tr#'+t).remove();
}

The solution that comes closest to what I want is that of the user rene limon. I need to know how your solution fits in this context.

<!DOCTYPE html>
<html>
<head>
    <title></title>

</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
tr{
  background: #ccc;
  cursor: pointer;
}
td{
  min-width: 125px;
  padding: 10px;
  text-align: center;
}
</style>
</head>
<body>
<table>
  <tr id="1">
    <td>1</td><td><a onclick="eliminar(this);">eliminar<a/></td>
  </tr>
  <tr id="2">
    <td>2</td><td><a onclick="eliminar(this);">eliminar<a/></td>
  </tr>
  <tr id="3">
    <td>3</td><td><a onclick="eliminar(this);">eliminar<a/></td>
  </tr>
  <tr id="4">
    <td>4</td><td><a onclick="eliminar(this);">eliminar<a/></td>
  </tr>
</table>
</body>

function eliminar(t) {
  var len = document.getElementById("detalle").length; //multiselect
  var i = t;

  if (i >= 0) {

    for (var j = i; j < len; j++) {
      var paso_text = document.getElementById("detalle").options[j].text;
      var paso_value = document.getElementById("detalle").options[j].value;

      document.getElementById("detalle").options[j].text = document.getElementById("detalle").options[j + 1].text;
      document.getElementById("detalle").options[j].value = document.getElementById("detalle").options[j + 1].value;
      document.getElementById("detalle").options[j + 1].text = paso_text;
      document.getElementById("detalle").options[j + 1].value = paso_value;
    }
    document.getElementById("detalle").length = len - 1;
  } else {
    alert("!! Seleccione el producto a quitar !!");
  }

  $('#tabla_resumen tr#' + t).remove();
}
tr {
  background: #ccc;
  cursor: pointer;
}

td {
  min-width: 125px;
  padding: 10px;
  text-align: center;
}
<!DOCTYPE html>
<html>
<head>
	<title></title>

</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
tr{
  background: #ccc;
  cursor: pointer;
}
td{
  min-width: 125px;
  padding: 10px;
  text-align: center;
}
</style>
</head>
<body>
<table id='tabla_resumen'>
  <tr id="0">
    <td>1</td><td><a onclick="eliminar(0);">eliminar<a/></td>
  </tr>
  <tr id="1">
    <td>2</td><td><a onclick="eliminar(1);">eliminar<a/></td>
  </tr>
  <tr id="2">
    <td>3</td><td><a onclick="eliminar(2);">eliminar<a/></td>
  </tr>
  <tr id="3">
    <td>4</td><td><a onclick="eliminar(3);">eliminar<a/></td>
  </tr>
</table> 
<script type="text/javascript">
function eliminar(e){
	alert(e);
  var parent = $("tabla_resumen tr#"+e).parent();
  $("#tabla_resumen tr#"+e).remove();
  parent.children("#tabla_resumen tr").each(function(i){
       ("#tabla_resumen tr").attr('id', (i+1));
       ("#tabla_resumen tr").children().text((i+1));
  });
}
</script>
</body>
    
asked by user2820116 18.01.2018 в 15:55
source

3 answers

3

Changing the IDs is cumbersome and not very recommendable. If you want to add / delete the row of the table that corresponds to the multiselect option, you could choose several options without having to rearrange the IDs. Here I leave you two:

  • Make the option have a data-attribute that points to the ID of the row to be created / deleted and act accordingly when they are selected / deselected.
  • When you click on a option check what the index is and create / delete (depending on whether you have marked or unmasked) a row in the table in the same index position.
  • In neither of these two cases will you have to update the IDs of options or rows and you will save unnecessary problems that may arise when changing IDs.

    Here you can see a working example (of the first option):

    // cuando se cambia el valor del multiselect
    $("#miselect").on("change", function() {
      // para cada opción
      $(this).find("option").each(function() {
        var target = $(this).data("target");
        // si está marcada
        if ($(this).is(":checked")) {
          // si no existe una fila con ID igual al data-target, se crea
          if ($("#" + target).length == 0) {
            // aquí pondrías el código para crear la fila
            $("#mitabla").append("<tr id='"+target+"'><td>"+target+"</td></tr>");
          }
        }
        // si no está marcada y existe una fila con ID igual al data-target
        else if ($("#" + target).length > 0) {
          // se borra
          $("#" + target).remove();
        }
      });
    });
    select {
      width: 100px;
      height: 60px;
    }
    
    option {
      height: 20px;
    }
    
    table, tr, td, th {
      border: 1px solid gray;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <select id="miselect" multiple>
      <option value="1" data-target="tr-1">Opción 1</option>
      <option value="2" data-target="tr-2">Opción 2</option>
      <option value="3" data-target="tr-3">Opción 3</option>
      <option value="4" data-target="tr-4">Opción 4</option>
      <option value="5" data-target="tr-5">Opción 5</option>
    </select>
    
    <table id="mitabla">
      <tr>
        <th>
          Valor
        </th>
      </tr>
    </table>
        
    answered by 18.01.2018 в 18:10
    0

    What do you think of this?

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <title>Document</title>
    </head>
    
    <body>
        <table>
            <tr>
                <td>
                    <button id="1">Borrar</button>
                </td>
                <td>1</td>
            </tr>
            <tr>
                <td>
                    <button id="2">Borrar</button>
                </td>
                <td>2</td>
            </tr>
            <tr>
                <td>
                    <button id="3">Borrar</button>
                </td>
                <td>3</td>
            </tr>
            <tr>
                <td>
                    <button id="4">Borrar</button>
                </td>
                <td>4</td>
            </tr>
        </table>
    </body>
    <script>
        $(document).ready(function () {
            $("#1").on("click", function () {
                $(this).parent().parent().toggle();
                OrdenarFilas(1);
            });
            $("#2").on("click", function () {
                $(this).parent().parent().toggle();
                OrdenarFilas(2);
            });
            $("#3").on("click", function () {
                $(this).parent().parent().toggle();
                OrdenarFilas(3);
            });
            $("#4").on("click", function () {
                $(this).parent().parent().toggle();
                OrdenarFilas(4);
            });
        });
        function OrdenarFilas(fila) {
            var $fila = $("tr").get(fila);
            var $filaSiguiente = $($($fila).next().find("td").get(1)).text();
            console.log(parseInt($filaSiguiente) - 1);
            console.log($filaSiguiente);
            var cantidadTR = $("tr").length;
            for (var i = fila; i < cantidadTR; i++) {
                $($($("tr").get(i)).find("td").get(1)).text(parseInt($($($("tr").get(i)).find("td").get(1)).text()) - 1);
            }
        }
    </script>
    
    </html>
        
    answered by 18.01.2018 в 16:07
    0

    Here I include a code fragment with which you can achieve it:

    $("tr a").on("click", function(event) {
      event.preventDefault();
      var parent = $(this).closest("table");
      $(this).closest("tr").remove();
      // agrego que descienda hasta los tr y ahi hago la iteración
      parent.children("tbody").children("tr").each(function(i){
           $(this).attr('id', (i+1));
           $(this).children("td:nth-child(1)").text((i+1));
      });
    });
    tr{
      background: #ccc;
      cursor: pointer;
    }
    td{
      min-width: 125px;
      padding: 10px;
      text-align: center;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr id="1">
        <td>1</td>
        <td>
           <a>eliminar</a>
        </td>
      </tr>
      <tr id="2">
        <td>2</td>
        <td>
           <a>eliminar</a>
        </td>
      </tr>
      <tr id="3">
        <td>3</td>
        <td>
           <a>eliminar</a>
        </td>
      </tr>
      <tr id="4">
        <td>4</td>
        <td>
           <a>eliminar</a>
        </td>
      </tr>
    </table>

    The variable parent I use to save the reference of the element because when it disappears it disappears. I also change the text for visual reasons but if you want to see the ids changing it uses the browser inspector.

    Update

    With the function% co_of% of% co_of%:

    function eliminar(t)
    {
      var parent = $(t).closest("table");
      console.log( $(t).closest("table").prop("tagName") );
      $(t).closest("tr").remove();
      // agrego que descienda hasta los tr y ahi hago la iteración
      parent.children("tbody").children("tr").each(function(i){
           console.log("hogf");
           $(this).attr('id', (i+1));
           $(this).children("td:nth-child(1)").text((i+1));
      });
    
    }
    tr{
      background: #ccc;
      cursor: pointer;
    }
    td{
      min-width: 125px;
      padding: 10px;
      text-align: center;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr id="1">
        <td>1</td>
        <td>
           <a onclick="eliminar(this);">eliminar</a>
        </td>
      </tr>
      <tr id="2">
        <td>2</td>
        <td>
           <a onclick="eliminar(this);">eliminar</a>
        </td>
      </tr>
      <tr id="3">
        <td>3</td>
        <td>
           <a onclick="eliminar(this);">eliminar</a>
        </td>
      </tr>
      <tr id="4">
        <td>4</td>
        <td>
           <a onclick="eliminar(this);">eliminar</a>
        </td>
      </tr>
    </table>
        
    answered by 18.01.2018 в 17:39