Skip to content
Advertisement

JS event listner on int-only CSS class

I have the following problem:

I have the following code in PHP:

<?php
for($i = 0; $i < sizeof($floating_ips_json["floating_ips"]); $i++){
?>

<tr class="details-control-<?php echo $i; ?> cursor-pointer">
<td>Test</td>
<td><?php echo $i; ?></td>
</tr>

<script>
$('#table-overview').on('click',
'tr.details-control-<?php echo $i; ?>',
function() { ... }
</script>

<?php
}
?>

So the class of is: details-control-1, details-control-2 and so on

But it doesn’t work. If I use words-only for the details-control class, it works fine.

The goal is to create a table and trigger a JS action when a row is clicked.

Thank you for your help.

Advertisement

Answer

Please use a class and the power of jQuery

$(function() {
  const $table = $("#table-overview");
  const $rows = $(".details-control", $table)
  $rows.on("click", function() {
    $rows.removeClass("active")
    $(this).addClass("active");
  })
})
.details-control {
  cursor: pointer;
}

.active {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table id="table-overview">
  <tbody>
    <tr class="details-control">
      <td>Test</td>
      <td>1</td>
    </tr>
    <tr class="details-control">
      <td>Test</td>
      <td>2</td>
    </tr>
    <tr class="details-control">
      <td>Test</td>
      <td>3</td>
    </tr>
  </tbody>
</table>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement