Ad

Jquery To Select A Table Row On Click Doesn't Work

I'm trying to toggle the class "highlight" of a html table row on click using JQuery. The table is created using Django template language. The table works and shows up in my development server and the Jquery works on tables not created with Django template language. I don't get any errors when running the code, but it just doesn't do anything when i click on a table row. I'm not sure what The problem could be.

HTML

<style media="screen">


 .highlight {
    background-color: yellow;
    color: white;
    }

</style>

<div class="table-responsive">
  <table class="table table table-borderless" id="food_table">
    <thead>
      <tr>
        <th>#</th>
        <th>Description</th>
        <th>Price</th>
      </tr>
    </thead>
    <tbody>
      {% for order in orders %}
      <tr>
        <td>{{ order.pk }}</td>
        <td>{{ order.Price }}</td>
        <td>{{ order.Description }}</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

JQuery

$("#food_table tbody").on('click','tr',function() {
    $(this).toggleClass("highlight");
  });

Dummy Data

[
    {
        "pk": 9,
        "Description": "Pizza",
        "Price": "88.00"
    },
    {
        "pk": 10,
        "Description": "Steak",
        "Price": "130.50"
    },
    {
        "pk": 11,
        "Description": "Coca Cola",
        "Price": "25.95"
    },
    {
        "pk": 12,
        "Description": "Water",
        "Price": "15.00"
    }
]
Ad

Answer

Try to delegate it from the body

$("body").on('click','#food_table tbody tr',function() {
    $(this).toggleClass("highlight");
  });
Ad
source: stackoverflow.com
Ad