How can I loop through the rows of an HTML table and get the values with a button?
I have an example of a table that gets me the specific value of a cell when I click on the row, but what I require is that when I click on an ok button I get the values row x row:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#ok").click(function() {
var valores = "";
$(this).parents("tr").find("#numero").each(function() {
valores += $(this).html() + "\n";
});
console.log(valores);
alert(valores);
});
$(".boton").click(function() {
var valores = "";
// Obtenemos todos los valores contenidos en los <td> de la fila
// seleccionada
$(this).parents("tr").find("#numero").each(function() {
valores += $(this).html() + "\n";
});
console.log(valores);
alert(valores);
});
});
</script>
<table border="1" cellspacing="0" cellpadding="5" id="tbl">
<thead>
<tr>
<td>Nombre 1</td>
<td>Nombre 2</td>
<td>Apellido 1</td>
<td>Mantenimiento</td>
</tr>
</thead>
<tr>
<td id="numero">Kevin</td>
<td>Joseph</td>
<td>Ramos</td>
<td class="boton">coger valores de la fila</td>
</tr>
<tr>
<td id="numero">Viviana</td>
<td>Belen</td>
<td>Rojas</td>
<td class="boton">coger valores de la fila</td>
</tr>
<tr>
<td id="numero">Junior</td>
<td>Gerardo</td>
<td>Nosé</td>
<td class="boton">coger valores de la fila</td>
</tr>
</table>
<br>
<form action="">
<label for="">Nombre</label>
<input type="button" value="ok" id="ok" class="boton">
</form>
</body>
</html>
First of all, if you are going to refer to more than one element you should not use
ID
, otherwise you should useclases
.Also, note that the row buttons and the "ok" button have the same class, so clicking the "ok" button would enter both JQuery functions (the one directly referencing the by his
ID
and the one that referenced him by the classboton
). I have changed the class of the "ok" button toboton2
but you can call it whatever you want.I had previously misunderstood your question. I hope the example will now be useful to you: