ndury
ndury

Reputation: 71

jQuery + Django : get data from HTML table

I am struggling to obtain the text within a table using jQuery.

I have a HTML page set up as followed.

{% for element in list %}
<button class="btn btn-primary add" id="{{forloop.counter}}">Add</button>
<table class="table" id="myTable">
   <thead>
         <tr><td><h3>General information for {{ element.id }}</h3></td></tr>
   </thead>
   <tbody>
         <tr><td><label id='name-{{forloop.counter}}' class="label label-success" >{{ element.Name }}</label></td></tr>
         <tr><td><label id='address-{{forloop.counter}}' class="label label-success" >{{ element.Address }}</label></td></tr>
         <tr><td><label id='code-{{forloop.counter}}' class="label label-success" >{{ element.Code }}</label></td></tr>
   </tbody>
</table>
{% endfor %}
<script>
  $(".add").click(function(e) {
     var id = $(this).attr('id');
     var test = $("myTable tr td").each(function() {
         var name = $(this).find('#name-'+id).text();
         var address = $(this).find('#address-'+id).text();
         var code = $(this).find('#code-'+id).text();
         alert(name);
         alert(address);
         alert(code);
     });
  });
</script>

For every object in the list, there is a button and a table. his table contains several rows holding the list data. I wish to retrieve the text in the <tr> tags and submit them later using ajax.

What am I doing wrong?

Upvotes: 1

Views: 1439

Answers (1)

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5186

You need to change this line

$("myTable tr td")

to

$("#myTable tbody tr td") //missing pound sign & your tds are inside tbody

Upvotes: 1

Related Questions