I have an html table and in each record I place a checkbox. How could I do so that when I select some records with the checkbox I get the data of the row to send them through a form?
$(document).ready(function(){
$("input[type=checkbox]:checked").each(function(){
//cada elemento seleccionado
alert($(this).val());
});
});
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
</head>
<body>
<form id="formulario" name="formulario" action="">
<table>
<tr>
<td><input type="checkbox" name="elemento1" value="1"/></td>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
</tr>
<tr>
<td><input type="checkbox" name="elemento2" value="2"/></td>
<td>ddd</td>
<td>eee</td>
<td>fff</td>
</tr>
<tr>
<td><input type="checkbox" name="elemento3" value="3"/></td>
<td>ggg</td>
<td>hhh</td>
<td>iii</td>
</tr>
<tr>
<td><input type="checkbox" name="elemento4" value="4"/></td>
<td>jjj</td>
<td>kkk</td>
<td>lll</td>
</tr>
<tr>
<td><input type="checkbox" name="elemento5" value="5"/></td>
<td>mmm</td>
<td>nnn</td>
<td>ooo</td>
</tr>
<tr>
<td><input type="checkbox" name="elemento6" value="6"/></td>
<td>ppp</td>
<td>qqq</td>
<td>rrr</td>
</tr>
<tr>
<td><input type="checkbox" name="elemento7" value="7"/></td>
<td>sss</td>
<td>ttt</td>
<td>uuu</td>
</tr>
<tr>
<td><input type="checkbox" name="elemento8" value="8"/></td>
<td>vvv</td>
<td>www</td>
<td>xxx</td>
</tr>
<tr>
<td><input type="checkbox" name="elemento9" value="9"/></td>
<td>yyy</td>
<td>zzz</td>
<td>AAA</td>
</tr>
<tr>
<td><input type="checkbox" name="elemento10" value="10"/></td>
<td>BBB</td>
<td>CCC</td>
<td>DDD</td>
</tr>
</table>
<input type="submit" value="seleccionar" onclick=""/>
</form>
</body>
</html>
In the previous example I only get the check value but not the whole row. What could I do?
I assume that the values you want to obtain are the texts that are in each
td
of the rows of the checkbox, for which we will search the DOM for thetd
"parent" of the selected checkbox and then find the othertd
adjacent ones:Modification to get the selected values as a string, separated by spaces:
Modification (again), to get a single string with all selected values:
With your code as such, at first it will not show anything, I suppose you do it with a function, the only thing that modifies your code is the
alert
.I'll explain what it does, The element
this
corresponds to thecheck
selected one:Now, since you are in an element that has no siblings, so to speak, you will have to go up a level with
parent()
Now we have siblings with the parent of the selected element, here we still cannot access the sibling elements, so we will have to go up another parent level
After the
parent()
you should look for the element with.find('td')
At this level we can already access all the elements
<td>
with which we can access with.eq(0)
,.eq(1)
, etc. prior tohtml()