jQuery + Django : get data from HTML table

时间:2021-04-13 22:53:16

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

我正在努力使用jQuery获取表中的文本。

I have a HTML page set up as followed.

我有一个HTML页面设置如下。

{% 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.

对于列表中的每个对象,都有一个按钮和一个表。他的表包含几行保存列表数据。我希望检索标签中的文本,然后使用ajax提交它们。

What am I doing wrong?

我究竟做错了什么?

1 个解决方案

#1


1  

You need to change this line

你需要改变这一行

$("myTable tr td")

to

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

#1


1  

You need to change this line

你需要改变这一行

$("myTable tr td")

to

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