Reputation: 2050
I'm new in JS and currently trying to get <th>
id to make it as part of <td>
and stack on attempting to get the id for my table created dynamically.
<table id='table'>
<thead>
<tr>
<th>Student</th>
<th id='Lesson_1'>Lesson 1</th>
<th id='Lesson_2'>Lesson 2</th>
<th id='Lesson_3'>Lesson 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jhon Doe</td>
<td><input type='checkbox' id='check1' onclick="checkIn(this.id);"> </td>
<td><input type='checkbox' id='check2' onclick="checkIn(this.id);"> </td>
<td><input type='checkbox' id='check3' onclick="checkIn(this.id);"> </td>
</tbody>
</table>
<script>
function checkIn(checkBoxId){
var checkBox = document.getElementById(checkBoxId);
var LessonID_checkBox = $('#table thead tr').find('th[id]').attr(id);
console.log(LessonID_checkBox);
</script>
UPD: _Expected ouptut: Lesson_1check1_
The number of Lesson
columns depends on a number of lessons in a database. What I'm doing is play around with this code $('#table thead tr').find('th').attr(id);
, but seems can't understand how to do it.
Upvotes: 0
Views: 780
Reputation: 50291
You can loop over the tds
which are inside tbody
and get the relevant td from thead.Then get the id and append it
$("#table tbody tr td").each(function(i, v) {
let getIdFromTH = ($("#table thead tr th").eq(i).attr('id'))
let currID = $(v).find('input').attr('id');
let newId = getIdFromTH + "-Test "
$(v).find('input').attr('id', newId)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='table'>
<thead>
<tr>
<th>Student</th>
<th id='I_WANT_THAT_ID'>Lesson</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jhon Doe</td>
<td><input type='checkbox' id='BE_HERE+something'> attandance </td>
</tbody>
</table>
Upvotes: 0
Reputation: 15130
Not sure if you are trying to get just the one specific th id or the id for any and all th elements. If looking to get them all, then you will need to select the th elements and then loop through to get each id. Something like:
var headings = $('#table thead th');
headings.each(function() {
alert(this.id);
});
Upvotes: 1
Reputation: 2269
You should be able to do the same thing using attributes like this:
$("th[id]");
If you want to get a with a specific id, you can use this:
$("th[id='I_WANT_THAT_ID']");
Upvotes: 1