2

Estoy estoy generando una lista con un input de tipo button esta lista se genera de una bd que tengo con 4 datos por consiguiente me genera 4 botones los cuales le he dado un identificador "alum[i].ID_EVENTO " que es un numero 1,2,3,4 como puedo sacar el valor de cada uno de esos botones adjunto el html y JavaScript

<body>
<div class="col-lg-7">
    <input id="myInput" type="text" placeholder="Search..">

    <table class="table" >
    <tbody id="myTable">
         <tr>
            <td>ID_EVENTO</td>
            <td>NOMBRE_EVENTO</td>
            <td>FECHA</td>
             <td>RESUMEN</td>
             <td>DESCRIPCION</td>
             <td>CATEGORIA</td>
             <td>SEDE</td>
             <td>LUGAR</td>
             <td>CUPOS</td>
             <td>DURACION_HORAS</td>
             <td>FACULTAD</td>
             <td>CREDITOS</td>
             <td>Agregar</td>
        </tr>

    </tbody>
    </table>
</div>



</body>

Js

  var url ='/api/api.php';
   var h;
    var listusers =$('.table');
        $.ajax({
             url: url,
             method:'GET',
             type: 'JSON'
        }).done(function (alumnos) {
           var alum = JSON.parse(alumnos);
           $.each(alum,function (i,item) {

               listusers.append('<tr ><td>'+ alum[i].ID_EVENTO + '</td>'  + '<td>'+ alum[i].NOMBRE_EVENTO + '</td>' +  '<td>' + alum[i].FECHA + '<td>'+ alum[i].RESUMEN + '</td>' + '<td>'+ alum[i].DESCRIPCION + '</td>' + '<td>'+ alum[i].CATEGORIA + '</td>' + '<td>'+ alum[i].SEDE + '</td>'+ '<td>'+ alum[i].LUGAR + '</td>'+ '<td>'+ alum[i].CUPOS + '</td>'+ '<td>'+ alum[i].DURACION_HORAS + '</td>'+ '<td>'+ alum[i].FACULTAD + '</td>'+ '<td>'+ alum[i].CREDITOS + '</td>' + "<td><input type='button' id=\"btn btn-info\" class='boton"+i+"'   value="+ alum[i].ID_EVENTO +" >  </input> </td>");;

               h=i;
           });
            });
        });
}

3 respuestas 3

2

Estás poniendo mal los parámetros de la llamada Ajax. En vez de:

$.ajax({
  url: url,
  method:'GET',
  type: 'JSON'
})

Debiera ser

$.ajax({
  url: url,
  type:'GET',
  dataType: 'json'
})

Suponiendo que tu backend devuelve JSON tal como lo estás pidiendo, y no texto, también podrías saltarte el parseo. Pero bueno, supongamos que recibes simplemente texto del backend así que debes parsearlo. Tenemos entonces que alum es un array de 4 elementos, cada uno de los cuales es un objeto con llaves ID_EVENTO, NOMBRE_EVENTO etc.

Separando el append que haces a tu tabla, tenemos que en una parte pones

'<td>' + alum[i].FECHA + '<td>'+ alum[i].RESUMEN + '</td>'

Falta el tag de cierre para la celda de fecha.

Más adelante, al añadir el botón, pones:

"<td><input type='button' id=\"btn btn-info\" class='boton"+i+"'   value="+ alum[i].ID_EVENTO +" >  </input> </td>"

Estás poniéndole como ID lo que debiera ser clase, y como clase lo que debiera ser id:

"<td><input type='button' class=\"btn btn-info\" id='boton"+i+"'   value="+ alum[i].ID_EVENTO +" >  </input> </td>"

Finalmente, no estás poniendo el cierre de la fila (</tr>);

Para que quedase más limpio, yo declararía una variable que fuera el objeto alum[i] quedando:

var current_alum=alum[i];

listusers.append(
   '<tr>'+
   '<td>'+ current_alum.ID_EVENTO + '</td>' +
   '<td>'+ current_alum.NOMBRE_EVENTO + '</td>' +  
   '<td>'+ current_alum.FECHA + '</td>'+
   '<td>'+ current_alum.RESUMEN + '</td>' + 
   '<td>'+ current_alum.DESCRIPCION + '</td>' + 
   '<td>'+ current_alum.CATEGORIA + '</td>' + 
   '<td>'+ current_alum.SEDE + '</td>'+ 
   '<td>'+ current_alum.LUGAR + '</td>'+
   '<td>'+ current_alum.CUPOS + '</td>'+ 
   '<td>'+ current_alum.DURACION_HORAS + '</td>'+ 
   '<td>'+ current_alum.FACULTAD + '</td>'+
   '<td>'+ current_alum.CREDITOS + '</td>' + 
   '<td><input type="button" class="btn btn-info" id="boton'+i+'"   value="'+ current_alum.ID_EVENTO +'" >  </input> </td>'+
   '</tr>');

El listener para obtener el valor del botón puedes añadirlo ahí mismo dentro del bucle

$('#boton'+i).on('click',function(){
    console.log($(this).val()); //obtener el valor del input
});

o delegarlo afuera como te mostró @Dev.Joel

listusers.on('click','.btn', function(){
    console.log($(this).val()); //obtener el valor del input
});
1
  • Muchas gracias ya me funciono
    – William T
    el 7 nov. 2017 a las 2:28
2

Para obtener el valor del input , podría añadir una clase global (selection) . a estos elementos y así añadir el listener a todos. (En su código debe reemplazar id por class para el input).

Además en el $.each debería emplear la variable item que sería equivalente a alum[i]

$(function() {
    var url ='/api/api.php';
    var listusers =$('.table');
    $.ajax({
             url: url,
             method:'GET',
             type: 'JSON'
        }).done(function (alumnos) {
           $.each(JSON.parse(alumnos),function (i,item) {
               listusers.append('<tr ><td>'+ item.ID_EVENTO + '</td>'  + '<td>'+ item.NOMBRE_EVENTO + '</td>' +  '<td>' + item.FECHA + '<td>'+ item.RESUMEN + '</td>' + '<td>'+ item.DESCRIPCION + '</td>' + '<td>'+ item.CATEGORIA + '</td>' + '<td>'+ item.SEDE + '</td>'+ '<td>'+ item.LUGAR + '</td>'+ '<td>'+ item.CUPOS + '</td>'+ '<td>'+ item.DURACION_HORAS + '</td>'+ '<td>'+ item.FACULTAD + '</td>'+ '<td>'+ item.CREDITOS + '</td>' + "<td><input type='button' class=\"btn btn-info selection\"   value="+ item.ID_EVENTO +" >  </input> </td>");;
           });
    });

    //Listener a los elementos con la clase que se añadió 
    $(document).on('click','.selection',function(){
        console.log($(this).val()); //obtener el valor del input
    });
});
3
  • Eso no va a funcionar. Deberías asociar la función al evento dentro de la función del done. Tal y como está cuando se ejecuta la instrucción para asociar el handler al evento click los botones aún no están definidos. el 6 nov. 2017 a las 8:29
  • @AsierVillanueva sí funcionaría, el evento está delegado en document que sí existe
    – ffflabs
    el 6 nov. 2017 a las 10:10
  • Cierto. Perdón. Por responder a la carrera :D el 6 nov. 2017 a las 10:18
0

Por lo que veo al final cada input te queda con clase "boton1", "boton2" y así...

Puedes hacer referencia a esa clase para cada botón y usas .val() para obtener el valor.

var valor1 = $('boton1').val();
var valor2 = $('boton2').val();
var valor3 = $('boton3').val();
var valor4 = $('boton4').val();

Saludos

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.