devopsEMK devopsEMK - 3 months ago 10
jQuery Question

Jquery select each checkbox's value when it's in a html table

HTML CODE

<table id="tablechkbx">
<tr>
<td>CITY&nbsp;<input value="5" id="datacell" type="checkbox"></td>
<td>DATE OF BIRTH&nbsp;<input value="7" id="datacell" type="checkbox"></td>
<td>DESIGNATION&nbsp;<input value="10" id="datacell" type="checkbox"></td>
<td>EMAIL&nbsp;<input value="1" id="datacell" type="checkbox"></td>
<td>GENDER&nbsp;<input value="12" id="datacell" type="checkbox"></td>
<td>INCOME LEVEL&nbsp;<input value="8" id="datacell" type="checkbox"></td>
<td>INDUSTRY OF EMPLOY&nbsp;<input value="9" id="datacell" type="checkbox"></td>
</tr>
<tr>
<td>KIDS&nbsp;<input value="13" id="datacell" type="checkbox"></td>
<td>MARITAL STATUS&nbsp;<input value="11" id="datacell" type="checkbox"></td>
<td>MOBILE NUMBER&nbsp;<input value="2" id="datacell" type="checkbox"></td>
<td>NAME&nbsp;<input value="3" id="datacell" type="checkbox"></td>
<td>NIC NUMBER&nbsp;<input value="6" id="datacell" type="checkbox"></td>
<td>TELEPHONE NUMBER&nbsp;<input value="4" id="datacell" type="checkbox"></td>
</tr>
</table>


Jquery

<script>
var tds;
$(document).ready(function(){
$('#btnselectall').on('click',function(){
$('#tablechkbx').find('tr').each(function(){
tds = $(this).find('td');
for(var k=0;k<tds.size();k++){
var data = tds[i];
console.log(data.next("#datacell").val());
}
});
});
});
</script>


I was try to get the checkbox value from above code but it's show an error like
TypeError: data.next is not a function
. But it will print all
td
element when it's use as
console.log(data);

Answer

Aside from the issues I mentioned in the comments, the reason you are getting TypeError: data.next is not a function is because when you use bracket notation and access a jQuery object like an array, it returns the DOM element at that position, not a jQuery object. If you change var data = tds[i]; to var data = tds.eq(i); you will get a jQuery object.

Another way to loop over them would be to use tds.each(callback) (docs).

An additional issue is that you would need to call data.children() instead of data.next() (assuming you've fixed data to be a jQuery object) since the input you are looking for is a child of the td not a sibling.