How to clean a data to take another one in jquery?

2

I have a select in html that when I choose an option automatically by means of a ajax it goes to php and it responds me in json and it shows me the corresponding data of that id of the option I chose in datatable .

How can I avoid that when I select another option of select of html that obviously already contains another id I continue to feed the table.

That is, whenever I choose an option, it feeds me the table with all the data contained in each id .

$("#grupo").change(function(){
        $("#estudiantes").find('option').remove();


            $.ajax({
                    url: 'listar_estudiantes',
                    type: 'POST',
                    data: {public_id:this.value}
                })
            .done(function(respuesta) {
                    var resultado = $.parseJSON(respuesta);
                    console.log(resultado);         

                    for (var i = resultado.length - 1; i >= 0; i--) 
                    {
                        var rowNode = tabla_estudiantes
                       .row.add([
                                    resultado[i].id_estudiante,
                                    resultado[i].nombre,
                                    resultado[i].apellido,
                                    resultado[i].nombre,
                                    resultado[i].grupo,
                                    resultado[i].nivel_estudio,
                                    "<center><button class='btn btn-warning' name='ver_estudiante' id='ver_estudiante'><span class='glyphicon glyphicon-eye-open'></span></button>",                    
                                ])
                       .draw()
                       .node();
                    }
                })
            .fail(function() {
                console.log("error");
                });
            });
    
asked by JDavid 02.01.2017 в 23:48
source

3 answers

1

There is no need to delete select for changes to be made and to erase the table you would do this:

  • Save the generated table with the plugin in a variable

    var table = $('#example').DataTable({});
    
  • Having the variable saved now if within the function of select delete the data from the table with:

    table.clear().draw()
    
  • Once the table is clean, we add the new data in the same way as you do.

    for (var i = resultado.length - 1; i >= 0; i--) 
    {
      tabla.row.add([
        resultado[i].id_estudiante,
        resultado[i].nombre,
        resultado[i].apellido,
        resultado[i].nombre,
        resultado[i].grupo,
        resultado[i].nivel_estudio,
        "<center><button class='btn btn-warning' name='ver_estudiante' id='ver_estudiante'><span class='glyphicon glyphicon-eye-open'></span></button>",                    
      ]).draw().node();
    }
    
  • Simple example

    var table = $('#example').DataTable({});
    $('#Cambio').on('change',function(e){
      console.log(this.value)
      table.clear().draw()//limpiamos la tabla
      console.log('Cambio de Informacion')
      table.row.add([
            "Opcion Uno",
            "System Architect",
            "$3,120",
            "2011/04/25",
            "Edinburgh",
            "5421"
        ]).draw();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
    <link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet"/>
    <select id="Cambio">
      <option>uno</option>
      <option>dos</option>
    </select>
    <table id="example" class="display" cellspacing="0" width="100%">
      <thead>
        <tr>
          <th>Name</th>
          <th>Position</th>
          <th>Office</th>
          <th>Age</th>
          <th>Start date</th>
          <th>Salary</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Tiger Nixon</td>
          <td>System Architect</td>
          <td>Edinburgh</td>
          <td>61</td>
          <td>2011/04/25</td>
          <td>$320,800</td>
        </tr>
        <tr>
          <td>Garrett Winters</td>
          <td>Accountant</td>
          <td>Tokyo</td>
          <td>63</td>
          <td>2011/07/25</td>
          <td>$170,750</td>
        </tr>
        <tr>
          <td>Ashton Cox</td>
          <td>Junior Technical Author</td>
          <td>San Francisco</td>
          <td>66</td>
          <td>2009/01/12</td>
          <td>$86,000</td>
        </tr>
        <tr>
          <td>Cedric Kelly</td>
          <td>Senior Javascript Developer</td>
          <td>Edinburgh</td>
          <td>22</td>
          <td>2012/03/29</td>
          <td>$433,060</td>
        </tr>
        <tr>
          <td>Airi Satou</td>
          <td>Accountant</td>
          <td>Tokyo</td>
          <td>33</td>
          <td>2008/11/28</td>
          <td>$162,700</td>
        </tr>
        <tr>
          <td>Brielle Williamson</td>
          <td>Integration Specialist</td>
          <td>New York</td>
          <td>61</td>
          <td>2012/12/02</td>
          <td>$372,000</td>
        </tr>
        <tr>
          <td>Herrod Chandler</td>
          <td>Sales Assistant</td>
          <td>San Francisco</td>
          <td>59</td>
          <td>2012/08/06</td>
          <td>$137,500</td>
        </tr>
        <tr>
          <td>Rhona Davidson</td>
          <td>Integration Specialist</td>
          <td>Tokyo</td>
          <td>55</td>
          <td>2010/10/14</td>
          <td>$327,900</td>
        </tr>
        <tr>
          <td>Colleen Hurst</td>
          <td>Javascript Developer</td>
          <td>San Francisco</td>
          <td>39</td>
          <td>2009/09/15</td>
          <td>$205,500</td>
        </tr>
      </tbody>
    </table>
        
    answered by 03.01.2017 в 01:19
    1

    If you want to clean the table by selecting another id ...

    Change this line:

     $("#estudiantes").find('option').remove();
    

    By the following:

     $("#estudiantes").html('');//Con esto limpias todos lo que contenga ese objeto, suponiendo que #estudiantes es tu <table>
    

    Review the sample code:

    $(document).ready(function() {
      $("#grupo").change(function(){
        var valor = $(this).val();
        console.log(valor);
        AgregarValores(valor)
        
      });
    });
    
    
    function AgregarValores(valor) {
       $("#estudiantes").html(''); // Esta linea hace lo que necesitas
      for (var i = 0; i < 4; i++) {
        var renglon = '<tr>';
        renglon = renglon + '<td> Renglon ' + (i+1) + '</td>';
        renglon = renglon + '<td> Estudiante ' + valor + '</td>';
        renglon = renglon + '</tr>';
        $("#estudiantes").append(renglon);
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <select id="grupo">
      <option value=1>Uno</option>
      <option value=2>Dos</option>
    </select>
    <table id="estudiantes">
    
    </table>

    In response to your comment:

    I attach the same example with jquery DataTables

    $(document).ready(function() {
      //Inicializo el grid con TODOS los datos
      FiltrarDatos('');
      AgregarValores()
        
      $("#grupo").change(function() {
        var valor = $(this).val();
        //console.log(valor);
    
        FiltrarDatos(valor);
        AgregarValores()
    
      });
    });
    
    
    function AgregarValores() {
      //$('#estudiantes').DataTable().clear().draw();//Con esto se limpia el data table
    
      $('#estudiantes').DataTable({
        destroy: true,
        data: datosFiltrados,
        columns: [{
          data: 'id'
        }, {
          data: 'nombre'
        }, {
          data: 'puesto'
        }, {
          data: 'ciudad'
        }]
      });
    }
    
    var datosFiltrados = [];
    
    function FiltrarDatos(filtro) {
      datosFiltrados = [];
      $.each(data.data, function(i, v) {
        if (v[2] == filtro || filtro == '') {
          var df = {
            id: i+1,
            nombre: v[0],
            puesto: v[1],
            ciudad: v[2]
          };
          datosFiltrados.push(df);
        }
      });
    
      console.log(filtro + ":" + datosFiltrados.length)
      return datosFiltrados;
    }
    
    var data = {
      "data": [
        [
          "Tiger Nixon",
          "System Architect",
          "Edinburgh",
          "5421",
          "2011/04/25",
          "$320,800"
        ],
        [
          "Garrett Winters",
          "Accountant",
          "Tokyo",
          "8422",
          "2011/07/25",
          "$170,750"
        ],
        [
          "Ashton Cox",
          "Junior Technical Author",
          "San Francisco",
          "1562",
          "2009/01/12",
          "$86,000"
        ],
        [
          "Cedric Kelly",
          "Senior Javascript Developer",
          "Edinburgh",
          "6224",
          "2012/03/29",
          "$433,060"
        ],
        [
          "Airi Satou",
          "Accountant",
          "Tokyo",
          "5407",
          "2008/11/28",
          "$162,700"
        ],
        [
          "Brielle Williamson",
          "Integration Specialist",
          "New York",
          "4804",
          "2012/12/02",
          "$372,000"
        ],
        [
          "Herrod Chandler",
          "Sales Assistant",
          "San Francisco",
          "9608",
          "2012/08/06",
          "$137,500"
        ],
        [
          "Rhona Davidson",
          "Integration Specialist",
          "Tokyo",
          "6200",
          "2010/10/14",
          "$327,900"
        ],
        [
          "Colleen Hurst",
          "Javascript Developer",
          "San Francisco",
          "2360",
          "2009/09/15",
          "$205,500"
        ],
        [
          "Sonya Frost",
          "Software Engineer",
          "Edinburgh",
          "1667",
          "2008/12/13",
          "$103,600"
        ],
        [
          "Jena Gaines",
          "Office Manager",
          "London",
          "3814",
          "2008/12/19",
          "$90,560"
        ],
        [
          "Quinn Flynn",
          "Support Lead",
          "Edinburgh",
          "9497",
          "2013/03/03",
          "$342,000"
        ],
        [
          "Charde Marshall",
          "Regional Director",
          "San Francisco",
          "6741",
          "2008/10/16",
          "$470,600"
        ],
        [
          "Haley Kennedy",
          "Senior Marketing Designer",
          "London",
          "3597",
          "2012/12/18",
          "$313,500"
        ],
        [
          "Tatyana Fitzpatrick",
          "Regional Director",
          "London",
          "1965",
          "2010/03/17",
          "$385,750"
        ],
        [
          "Michael Silva",
          "Marketing Designer",
          "London",
          "1581",
          "2012/11/27",
          "$198,500"
        ],
        [
          "Paul Byrd",
          "Chief Financial Officer (CFO)",
          "New York",
          "3059",
          "2010/06/09",
          "$725,000"
        ],
        [
          "Gloria Little",
          "Systems Administrator",
          "New York",
          "1721",
          "2009/04/10",
          "$237,500"
        ],
        [
          "Bradley Greer",
          "Software Engineer",
          "London",
          "2558",
          "2012/10/13",
          "$132,000"
        ],
        [
          "Dai Rios",
          "Personnel Lead",
          "Edinburgh",
          "2290",
          "2012/09/26",
          "$217,500"
        ],
        [
          "Jenette Caldwell",
          "Development Lead",
          "New York",
          "1937",
          "2011/09/03",
          "$345,000"
        ],
        [
          "Yuri Berry",
          "Chief Marketing Officer (CMO)",
          "New York",
          "6154",
          "2009/06/25",
          "$675,000"
        ],
        [
          "Caesar Vance",
          "Pre-Sales Support",
          "New York",
          "8330",
          "2011/12/12",
          "$106,450"
        ],
        [
          "Doris Wilder",
          "Sales Assistant",
          "Sidney",
          "3023",
          "2010/09/20",
          "$85,600"
        ],
        [
          "Angelica Ramos",
          "Chief Executive Officer (CEO)",
          "London",
          "5797",
          "2009/10/09",
          "$1,200,000"
        ],
        [
          "Gavin Joyce",
          "Developer",
          "Edinburgh",
          "8822",
          "2010/12/22",
          "$92,575"
        ],
        [
          "Jennifer Chang",
          "Regional Director",
          "Singapore",
          "9239",
          "2010/11/14",
          "$357,650"
        ],
        [
          "Brenden Wagner",
          "Software Engineer",
          "San Francisco",
          "1314",
          "2011/06/07",
          "$206,850"
        ],
        [
          "Fiona Green",
          "Chief Operating Officer (COO)",
          "San Francisco",
          "2947",
          "2010/03/11",
          "$850,000"
        ],
        [
          "Shou Itou",
          "Regional Marketing",
          "Tokyo",
          "8899",
          "2011/08/14",
          "$163,000"
        ],
        [
          "Michelle House",
          "Integration Specialist",
          "Sidney",
          "2769",
          "2011/06/02",
          "$95,400"
        ],
        [
          "Suki Burks",
          "Developer",
          "London",
          "6832",
          "2009/10/22",
          "$114,500"
        ],
        [
          "Prescott Bartlett",
          "Technical Author",
          "London",
          "3606",
          "2011/05/07",
          "$145,000"
        ],
        [
          "Gavin Cortez",
          "Team Leader",
          "San Francisco",
          "2860",
          "2008/10/26",
          "$235,500"
        ],
        [
          "Martena Mccray",
          "Post-Sales support",
          "Edinburgh",
          "8240",
          "2011/03/09",
          "$324,050"
        ],
        [
          "Unity Butler",
          "Marketing Designer",
          "San Francisco",
          "5384",
          "2009/12/09",
          "$85,675"
        ],
        [
          "Howard Hatfield",
          "Office Manager",
          "San Francisco",
          "7031",
          "2008/12/16",
          "$164,500"
        ],
        [
          "Hope Fuentes",
          "Secretary",
          "San Francisco",
          "6318",
          "2010/02/12",
          "$109,850"
        ],
        [
          "Vivian Harrell",
          "Financial Controller",
          "San Francisco",
          "9422",
          "2009/02/14",
          "$452,500"
        ],
        [
          "Timothy Mooney",
          "Office Manager",
          "London",
          "7580",
          "2008/12/11",
          "$136,200"
        ],
        [
          "Jackson Bradshaw",
          "Director",
          "New York",
          "1042",
          "2008/09/26",
          "$645,750"
        ],
        [
          "Olivia Liang",
          "Support Engineer",
          "Singapore",
          "2120",
          "2011/02/03",
          "$234,500"
        ],
        [
          "Bruno Nash",
          "Software Engineer",
          "London",
          "6222",
          "2011/05/03",
          "$163,500"
        ],
        [
          "Sakura Yamamoto",
          "Support Engineer",
          "Tokyo",
          "9383",
          "2009/08/19",
          "$139,575"
        ],
        [
          "Thor Walton",
          "Developer",
          "New York",
          "8327",
          "2013/08/11",
          "$98,540"
        ],
        [
          "Finn Camacho",
          "Support Engineer",
          "San Francisco",
          "2927",
          "2009/07/07",
          "$87,500"
        ],
        [
          "Serge Baldwin",
          "Data Coordinator",
          "Singapore",
          "8352",
          "2012/04/09",
          "$138,575"
        ],
        [
          "Zenaida Frank",
          "Software Engineer",
          "New York",
          "7439",
          "2010/01/04",
          "$125,250"
        ],
        [
          "Zorita Serrano",
          "Software Engineer",
          "San Francisco",
          "4389",
          "2012/06/01",
          "$115,000"
        ],
        [
          "Jennifer Acosta",
          "Junior Javascript Developer",
          "Edinburgh",
          "3431",
          "2013/02/01",
          "$75,650"
        ],
        [
          "Cara Stevens",
          "Sales Assistant",
          "New York",
          "3990",
          "2011/12/06",
          "$145,600"
        ],
        [
          "Hermione Butler",
          "Regional Director",
          "London",
          "1016",
          "2011/03/21",
          "$356,250"
        ],
        [
          "Lael Greer",
          "Systems Administrator",
          "London",
          "6733",
          "2009/02/27",
          "$103,500"
        ],
        [
          "Jonas Alexander",
          "Developer",
          "San Francisco",
          "8196",
          "2010/07/14",
          "$86,500"
        ],
        [
          "Shad Decker",
          "Regional Director",
          "Edinburgh",
          "6373",
          "2008/11/13",
          "$183,000"
        ],
        [
          "Michael Bruce",
          "Javascript Developer",
          "Singapore",
          "5384",
          "2011/06/27",
          "$183,000"
        ],
        [
          "Donna Snider",
          "Customer Support",
          "New York",
          "4226",
          "2011/01/25",
          "$112,000"
        ]
      ]
    }
    <link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js">
    </script>
    
    
    <select id="grupo">
      <option value=''></option>
      <option value='New York'>New York</option>
      <option value='Tokyo'>Tokyo</option>
      <option value='London'>London</option>
    </select>
    <table id="estudiantes">
      <thead>
        <tr>
          <th>Id</th>
          <th>Nombre</th>
          <th>Puesto</th>
          <th>Ciudad</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
        
    answered by 03.01.2017 в 00:53
    0

    To clean the table, simply remove each row by removeChild . You just have to call the function before adding the new records.

    function clearTable (id) {
      var tbody = document.getElementById(id);
      while (tbody.firstChild) {
        tbody.removeChild(tbody.firstChild);
      }
    }
    

    It can also be done with innerHTML but has a very low performance penalty compared to this way; although it usually has no major impact on regular applications.

    Then, before adding the new records to the table, you call this function by passing the id of the table to be cleaned, in your case, the student table.

    $.ajax({
      url: 'listar_estudiantes',
      type: 'POST',
      data: { public_id: this.value }
    })
    .done(function (estudiantes) {
      clearTable('tabla-estudiantes'); // llamamos a la función
      $.each(estudiantes, (estudiante) => {
        // agregas los estudiantes a la tabla
      });
    });
    
        
    answered by 03.01.2017 в 01:06