Warm tip: This article is reproduced from serverfault.com, please click

I'm not getting the specific value by id in jquery from the table row, it shows 'undefined'

发布于 2020-11-28 07:34:35

I'm trying to catch the value from the table row when clicking on the add to cart btn. The table is here.

<table class="table" id="myTable">
    <thead class="thead-dark">
       <tr>
          <th scope="col">ID</th>
            <th scope="col">Name</th>
            <th scope="col">Availability</th>
            <th scope="col">Price</th>
            <th scope="col">Category</th>
            <th scope="col">Type</th>
            <th scope="col">Vendor</th>
            <th scope="col">Handle</th>
           </tr>
      </thead>
      <tbody>

    <% for(var i=0; i < medicines.length; i++) { %>
      <tr>
         <th scope="row"><span id="id"><%= medicines[i].id %></span></th>
         <td><%= medicines[i].name %></td>
         <td><%= medicines[i].availability %></td>
         <td><%= medicines[i].price %></td>
         <td><%= medicines[i].category %></td>
         <td><%= medicines[i].type %></td>
       <td><%= medicines[i].vendor %></td>
         <td>
            <input type="number" id="availability" name="quantity" min="1" max="<%= medicines[i].availability %>" required>
                                               
            <input type="submit" id="btn" class="btn btn-secondary" value="Add to Cart">
         </td>
     </tr>
    <% } %>
                              
  </tbody>
</table>

and Jquery code is...

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


<script>
$(document).ready(() => {
            
    $("#myTable").on('click', '#btn', () => {
        var row = $(this).closest("tr");

        var col = row.find("#id").html();
        alert(col);
    });
            
});
</script>

I should get the value of the specific column of the row I click. But in the alert it shows undefined!

How can I get the value of id="id" from the row I click of the table?

Update: When I used function() {} inside the click event instead () => {} arrow function it worked!

Questioner
Saqib
Viewed
0
Saqib 2020-11-29 00:01:48

When I changed the code to this code below, it worked fine. Which I realized, the arrow function didn't work for me!

<script>
$(document).ready(function() {
   $("#btn").click(function() {
        
        var row = $(this).closest("tr");

        var col = row.find("#id").text();
        alert(col);
    });
});
</script>