I'm trying to get the span text when looping over table cells with no success.
<td>
<select name="newStatus" class="stChange">
<option value="0-596">active</option>
<option value="2-596">logout</option>
</select>
</td>
<td class="CellWithComment">
<input id="c57" type="checkbox" name="tfoza" value="1">
<label for="c57">
<span></span>
</label>
<span class="CellComment">960</span>
</td>
<td class="CellWithComment">
<input id="c58" type="checkbox" name="tfoza" value="1">
<label for="c58">
<span></span>
</label>
<span class="CellComment">901</span>
</td>
</tr>
jquery:
$('.stChange').on('change', function ()
{
var st = $(this).val();
var vls = st.split('-');
if( vls[0] == 0){
console.log('0',st);
$(this).closest('tr').find('input[type=checkbox]:checked').each(function(){
console.log($(this).find('.CellComment').text()) ;
});
}
if( vls[0] == 2){
}
});
I'm trying to find the span text when the checkbox is checked (JSFiddle).
What is wrong with the code?
This line of code $(this).find('.CellComment').text() was the problem. The find function looks for children and grand children etc inside of a parent element. That line of code is looking for .CellComment inside the checkbox, which the .each function is iterating through.
I have change that line of code to $(this).parent().find('.CellComment').text(). I have selected the parent of the checkbox using the parent() function, which selects the .CellWithComment element and then find the .CellComment element inside.
$('.stChange').on('change', function (event)
{
var st = $(this).val();
var vls = st.split('-');
if( vls[0] == 0){
$(event.target).closest('tr').find('input[type=checkbox]:checked').each(function() {
console.log($(this).parent().find('.CellComment').text());
});
}
if( vls[0] == 2){
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<table>
<tr>
<td class="test">
<select name="newStatus" class="stChange">
<option value="0-596">active</option>
<option value="2-596">logout</option>
</select>
</td>
<td class="CellWithComment">
<input id="c57" type="checkbox" name="tfoza" value="1">
<label for="c57">
<span></span>
</label>
<span class="CellComment">960</span>
</td>
<td class="CellWithComment">
<input id="c58" type="checkbox" name="tfoza" value="1">
<label for="c58">
<span></span>
</label>
<span class="CellComment">901</span>
</td>
</tr>
</table>