How to order the id's of the elements of a table - JS

0

in my code I add elements to a table using javascript.

function agregarAlumno(){
        var rut_alumno = $('#rut_alumno').val();
        var nombre_alumno = $('#nombre_alumno').val();

        $('#example1 tbody').append('<tr id='+rut_alumno+'><td><i class="fa fa-remove" onclick=deleteTr("'+rut_alumno+'")   ></i></td><td>'+rut_alumno+'</td><td>'+nombre_alumno+'</td></tr>');
    }

Now I do not know how to ask for the id of the elements of the table to pass them to an ajax.

    
asked by Gustavo 28.08.2017 в 15:46
source

2 answers

3

Recalling each tr of the table using the method .each(fn) and for each tr you get the attribute id, then save it in an array:

var ids = [];
$("#example tr").each(function(){
   ids.push(this.id); // agregas el id de cada tr al array
});

console.log(ids);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="example">
 <tr id="id1">
   <td>Prueba</td>
 </tr>
 <tr id="id2">
   <td>Prueba</td>
 </tr>
 <tr id="id3">
   <td>Prueba</td>
 </tr>
</table>
    
answered by 28.08.2017 / 15:55
source
0

In case you want it from pure Javascript:

// Objeto para pasar por AJAX
let idsFilas = {};

// Seleccionamos la tabla   
const tabla = document.getElementById("example");

// Obtenemos las filas
const filasTabla = tabla.rows;

// Obtenemos la longitud de las filas
const numeroFilasTabla = tabla.rows.length;

// Creamos el ciclo for
for (let i = 0;i < numeroFilasTabla; i++) {
    // Recorremos cada fila --> filasTabla[i];
    // Obtendremos:
    // <tr id="id1">...</tr>
    // Obtenemos el id --> filasTabla[i].id;
    // Insertamos los ids en el objeto
    // Cada propiedad sera 0,1,2,3 y como valor id1, id2, id3
    idsFilas[i] = filasTabla[i].id;
}

// Convertimos el objeto a JSON, formato estándar

let datos = JSON.parse(idsFilas);

// Obtenemos {"0":"id1","1":"id2","2":"id3"} 

// Ahora pasamos por AJAX:

$("#enviar").click(function() {
$.ajax({
        type:"post",
        url:"cargar.php",
        data:datos,
        dataType:"json",
        success: function(data) {
            // Acciones cuando funcione
        },
        error: function() {
            // Acciones cuando de error
        }
    }); 
});
    
answered by 28.08.2017 в 16:30