简体   繁体   English

如何使用jQuery从表行中选择数据

[英]How to select data from a table row with jQuery

I am trying to extract data in a row (I only need one column actually) while pressing the input button in the row. 我试图在按行中的输入按钮时提取一行中的数据(实际上我只需要一列)。 I used: 我用了:

$(document).ready(function() {
  var ttl_emp = $('#no_emp').text();
  var ttl_sal = $('#tl_sal').text();

  $('#wtable').on('click', 'input', function() {
    var rdata = $(this).parents('tr td:nth-child(8)').text();

    alert(rdata);
    ttl_sal = ttl_sal - c_emp_netSal;
    $(this).parents('tr').remove();
    $('#no_emp').text(ttl_emp - 1);
    ttl_emp = ttl_emp - 1;

    $('#tl_sal').text(ttl_sal);
  });
});

But failed and the console mentions undefined data. 但是失败了,并且控制台提到了未定义的数据。 wtable is the id of table. wtable是表的ID。

As your problem you can use this code to get data from selected row in table using jquery. 作为您的问题,您可以使用此代码使用jquery从表中的选定行获取数据。 This is sample code and try to understand this logic, after that you can implement in your code. 这是示例代码,请尝试理解此逻辑,然后再在代码中实现。 I hope it will be helpful for you. 希望对您有帮助。

Description We are use .find() function for getting right control in table. 描述我们使用.find()函数来获得对表的正确控制。 So if you have input type is text, then use .find('input[type="text"]') 因此,如果input类型是文本,则使用.find('input[type="text"]')

eq() is function to find using Index number, so if your column is first position in table then you should use eq(0) to get value of first column in table. eq()是使用索引号查找的函数,因此,如果您的列在表中位于第一位置,则应使用eq(0)获取表中第一列的值。 This Index number condition is apply for all sibling column's. 此索引号条件适用于所有同级列。

In this code we are used .val() for get value from textbox . 在此代码中,我们使用.val()textbox获取值。 If you want to get text from label then you should use .text() . 如果要从标签获取文本,则应使用.text()

Logic Here 这里的逻辑

$(document).ready(function(){
  $('#tableid tr').each(function(){
        var name = $(this).closest('td').find('input[type="text"]').eq(0).val();
  });
});

Your code with Logic 您的逻辑代码

$(document).ready(function() {
var ttl_emp = $('#no_emp').text();
var ttl_sal = $('#tl_sal').text();

$('#wtable tr').on('click', function() {
var rdata = $(this).find('td').eq(8).val(); // for label use val() otherwise for textbox use text() for get value

alert(rdata);
ttl_sal = ttl_sal - c_emp_netSal;
$('#no_emp').text(ttl_emp - 1);
ttl_emp = ttl_emp - 1;

$('#tl_sal').text(ttl_sal);
});
});

Live Demo 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM