How to get the value of the last element of a dynamic table, jquery?

0

In this way I generate the table dynamically:

var cupones_bienvenida_todos = $('.cupones_bienvenida_todos');
var tipoCupon ='';

$.each(response.data, function (i) {
  if (response.data[i].Tipo_cupon == 1){
    tipoCupon = "Cupón de 60%";
  }
  else if(response.data[i].Tipo_cupon == 1){
    tipoCupon = "Cupón de 80%";
  }
  else{
    tipoCupon = "Cupón de 100%";
  }

  $('<tr class="cupones"/>')
  .append($('<td/>').addClass('nuevo-td')
  .append($('<label/>').addClass('label-radio item-content')
    .text(response.data[i].Cod_Cliente + " - " + response.data[i].Nombre)))
  .append($('<td/>').addClass('label-cell nuevo-td').text(tipoCupon))
  .append('<div class="cod_cupon" style="display:none">' +
    response.data[i].Identificador + '</div>')
  .append('<div class="tipo_cupon" style="display:none">' +
    response.data[i].Tipo_cupon + '</div>')
  .append($('<td/>').addClass('label-cell nuevo-td')
  .append($('<label/>').addClass('label-checkbox item-content')
  .append('<input type="checkbox" name="cupon_check" class="cupon_check" value="' +
    response.data[i].Identificador + '"/>')
  .append($('<span/>').addClass('item-media')
    .append('<i class="icon icon-form-checkbox"></i>'))))
  .appendTo(cupones_bienvenida_todos);
  if (cantidad_llaves === 0) {
    $('.cupon_check').prop('disabled', true)
  }
});
llenarVista();

Suppose that from this table I generate 3 records, how can I get the value of class tipo_cupon of the last record that was generated? With this function I fill the table again, according to a JSON obtained and from this function is where I must obtain the last value of the table generated dynamically.

function llenarVista(){
  if(json_cupones_welcome){
    json_cupones_welcome_parse = JSON.parse(json_cupones_welcome);
    var identificador_cupon =0;
    var cupones = $('.cupones');
    var tipo_cupon; //60%, 80% y 100%
    $.each(json_cupones_welcome_parse.checkbox, function (index,value) {
      identificador_cupon = value.identificador;
      cupones.find(".cupon_check[value='"+identificador_cupon+"']")
        .prop('checked', true);

      $.each(value.productos_checkbox, function(index,producto){
        productos_seleccionados.push(producto);
        productos_checkbox_seleccionados.push(producto);
      });
      obj_checkbox_seleccionados.productos_checkbox = productos_checkbox_seleccionados;
    });
    //En esta linea es en donde estoy intentando obtener el ultimo valor
    tipo_cupon = cupones.find(".tipo_cupon").text();
    console.log("TIPO CUPON, DEL JSON RETORNADO");
    console.log(tipo_cupon);
    // Este console lo que hace es devolverme  el valor de la clase 'tipo_cupon'
    // pero de todos los registros, es decir si tengo 3 registros en la tabla dinamica,
    // en esta linea me imprime 3  veces el 'tipo_cupon'

    $.each(productos_seleccionados, function(index, value){
      identificador_cupon = value.codCupon;
      cupones.find(".cupon_check[value='"+identificador_cupon+"']")
        .prop('checked', true);
    });
    productosSeleccionados();
    $(".lista_productos_elegir > li").remove();
    $(".lista_productos_elegir3 > li").remove();
    $(".lista_productos_elegir4 > li").remove();
    cuponesDescuentoProducto1(idPedido);
    cuponesDescuentoProducto3(idPedido);
    cuponesDescuentoProducto4(idPedido);
    $('.tbla-productos1').show();
    $('.tbla-productos3').show();
    $('.tbla-productos4').show();
  }
}

Thank you very much in advance.

    
asked by JG_GJ 05.10.2018 в 19:41
source

3 answers

0

Just add the following:

tipo_cupon = cupones.find(".tipo_cupon").last();
console.log(tipo_cupon.text());
    
answered by 05.10.2018 в 20:20
0

Ok, I do not understand very well how are you structuring exactly your elements but I will try to make a minimum example to see if it is what you are looking for.

If you want to know what is the value of a last tag x that is the sister of other elements you just have to use last() .

This means that, you have your classes .tipo_cupon , if you structure it in the following way, you will find the last brother of the class.

As I do not know if it's the daughter of a specific element, I'll place it as if it were just a sister element:

  

Example:

$(".tipo_cupon").last().html();

// O

$(".tipo_cupon").last().text();

If you want to specify which parent element is just place the parent element inside the query selector:

  

Example

$("padre .tipo_cupon").last().html();
// ...

All this you execute after generating your table, or with a separate event.

I hope it helps you.

    
answered by 05.10.2018 в 20:30
0

I made a small code so you can guide yourself, the idea is this: create a array with values of name and surnames which will emulate the data that comes in your JSON , that array will fill the table initially, then create a button that says "Get the latest" which pressing it will give you the value of the last element; the last element is the one that has the class tipo_cupon , there are two a div and a input to guide you and see how you can get the value either a input , a div or any another element the notion is the same. Then create a button that says "add more records" which will allow you to continue filling the table emulating the process you describe of the dynamic, once you fill the table again you can click the button again > "Get the last one" and the result should be different and I think this would cover your question, I hope it's what you're looking for:

const array = [{"nombre":"David", "apellido":"Molina"},
               {"nombre":"Freddy", "apellido":"Molina"},
               {"nombre":"Carolina", "apellido":"Coronel"}];

const llenarTabla = (array) => {

  array.forEach((elemento) => {

    $("table")
    .append('<tr>
               <td>'+elemento.nombre+'</td>
               <td>'+elemento.apellido+'</td>
               <td>
                 <div class="tipo_cupon">'+elemento.nombre+' '+elemento.apellido+'</div>
               </td>
               <td>
                 <input class="tipo_cupon2" value="'+elemento.apellido+' '+elemento.nombre+'">
               </td>
             </tr>')

  });

} 

llenarTabla(array);

$("#obtener").on("click", function(){
  
  let val1 = $("table tr:last").find(".tipo_cupon").text();
  let val2 = $("table tr:last").find(".tipo_cupon2").val();
  
  alert("El último valor para el div con la clase .tipo_cupon es "+val1+" y para el input es "+val2);
  
});

$("#llenar").on("click", function(){
  
  let array = [{"nombre":"Carlos", "apellido":"Coronel"},
               {"nombre":"Ruth", "apellido":"Ruíz"},
               {"nombre":"Pastora", "apellido":"Marín"}];
  
  llenarTabla(array);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="obtener">Obtener el último</button>
<button id="llenar">agregar más registros</button>
<br><br>
<table border="1">
 <thead>
   <th>Nombre</th>
   <th>Apellido</th>
   <th>Nombre Completo div</th>
   <th>Nombre Completo input</th>
 </thead>
</table>
    
answered by 05.10.2018 в 21:13