简体   繁体   中英

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.

As your problem you can use this code to get data from selected row in table using 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. So if you have input type is text, then use .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. This Index number condition is apply for all sibling column's.

In this code we are used .val() for get value from textbox . If you want to get text from label then you should use .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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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