I'm a newbie with Javascript and I need to walk through the rows of a table and if checkbox
is checked, get the value of a column (ID) and store it in array
.
I'm a newbie with Javascript and I need to walk through the rows of a table and if checkbox
is checked, get the value of a column (ID) and store it in array
.
You did not enter the table structure, but no matter the structure, the code below will get the id
of the column you indicate in the variable:
var coluna = 3; // coluna em que está o ID
The code traverses each row of the table and verifies that there is a checkbox
checked; if it does, it will get the id
of the td
(column) entered in the variable above ( var coluna
) and insert in the var ids = [];
array.
See example:
$(document).ready(function(){
var ids = [];
var coluna = 2; // coluna em que está o ID
$("table tr").each(function(){
if($(this).find("input[type='checkbox']").is(":checked")){
ids.push($(this).find("td:eq("+(coluna-1)+")").attr("id"));
}
});
console.log(ids);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableborder="1">
<th>
Coluna 1
</th>
<th>
Coluna 2
</th>
<th>
Coluna 3
</th>
<tr>
<td id="linha1">
<input type="checkbox" />
</td>
<td id="linha1_1">
col 2, linha 1
</td>
<td id="linha1_2">
col 3, linha 1
</td>
</tr>
<tr>
<td id="linha2">
<input type="checkbox" checked />
</td>
<td id="linha2_1">
col 2, linha 2
</td>
<td id="linha2_2">
col 3, linha 2
</td>
</tr>
<tr>
<td id="linha3">
<input type="checkbox" checked />
</td>
<td id="linha3_1">
col 2, linha 3
</td>
<td id="linha3_2">
col 3, linha 3
</td>
</tr>
</table>