最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML Table onClick function to get table row key and value - Stack Overflow

programmeradmin3浏览0评论

I wanted to create a HTML table with onclick function to get the key and value of a row, so far the onclick function is working but it displaying and empty array for me, how can I fix this problem. Thanks.

I wanted it to be display in console log in this format when you click on the first row:

{ "name":"Clark", "age":29};

Here is my code

var table = document.getElementById("tableID");
if (table != null) {
  for (var i = 0; i < table.rows.length; i++) {
    table.rows[i].onclick = function() {
      tableText(this);
    };
  }
}

function tableText(tableRow) {
  var myJSON = JSON.stringify(tableRow);
  console.log(myJSON);
}
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
    <tr>
        <th hidden="hidden"></th>
        <th>name</th>
        <th>age</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td >Clark</td>
        <td>29</td>
    </tr>
    <tr>
        <td >Bruce</td>
        <td>30</td>
    </tr>
</tbody>
</table>

I wanted to create a HTML table with onclick function to get the key and value of a row, so far the onclick function is working but it displaying and empty array for me, how can I fix this problem. Thanks.

I wanted it to be display in console log in this format when you click on the first row:

{ "name":"Clark", "age":29};

Here is my code

var table = document.getElementById("tableID");
if (table != null) {
  for (var i = 0; i < table.rows.length; i++) {
    table.rows[i].onclick = function() {
      tableText(this);
    };
  }
}

function tableText(tableRow) {
  var myJSON = JSON.stringify(tableRow);
  console.log(myJSON);
}
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
    <tr>
        <th hidden="hidden"></th>
        <th>name</th>
        <th>age</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td >Clark</td>
        <td>29</td>
    </tr>
    <tr>
        <td >Bruce</td>
        <td>30</td>
    </tr>
</tbody>
</table>

Share edited Jun 2, 2017 at 2:32 M.Izzat asked Jun 2, 2017 at 2:01 M.IzzatM.Izzat 1,1664 gold badges22 silver badges54 bronze badges 6
  • You are passing a DOM element (i.e. a host object) to JSON.stringify, are you sure that should work? See How to serialize DOM node to JSON even if there are circular references?. – RobG Commented Jun 2, 2017 at 2:12
  • Hi @RobG thanks your reply, I guess I went to a wrong direction. My goal is to get the entire row object onClick so i can pass it later to edit a REST API Framework later. for now i just want to get the object in JSON format. can you help me with that. thanks – M.Izzat Commented Jun 2, 2017 at 2:18
  • The stringified (serialised) version of a TR would be its outerHTML, which can be passed as a string then parsed back to a DOM object using an HTML parser. I think JSON is the wrong tool in this case. – RobG Commented Jun 2, 2017 at 2:20
  • i see, any suggestion? – M.Izzat Commented Jun 2, 2017 at 2:21
  • Per the first ment, you can manually serialise the element but that seems a bit extreme. So either serialise just the bits you want, or use outerHTML. Perhaps you should explain what you mean by "key and value of a row", e.g. what should clicking on a row produce (sample output)? – RobG Commented Jun 2, 2017 at 2:22
 |  Show 1 more ment

4 Answers 4

Reset to default 1

I edited my answer to return the data as an object. Run the script and have a look.

var table = document.getElementById("tableID");
if (table) {
  for (var i = 0; i < table.rows.length; i++) {
    table.rows[i].onclick = function() {
      tableText(this);
    };
  }
}

function tableText(tableRow) {
  var name = tableRow.childNodes[1].innerHTML;
  var age = tableRow.childNodes[3].innerHTML;
  var obj = {'name': name, 'age': age};
  console.log(obj);
}
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
    <tr>
        <th hidden="hidden"></th>
        <th>name</th>
        <th>age</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td >Clark</td>
        <td>29</td>
    </tr>
    <tr>
        <td >Bruce</td>
        <td>30</td>
    </tr>
</tbody>
</table>

I think you can use tr.innerTestto get the value in the tags

If you are using jQuery you can add an eventlistener to the table like this

$('#tableID').on('click', 'tr', function(e){
  tableText($(this).html());
});

function tableText(tableRow) {
  var myJSON = JSON.stringify(tableRow);
  console.log(myJSON);
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<table align="center" id="tableID" border="1" style="cursor: pointer;">
  <tr>
    <td>Text</td>
    <td>MoreText</td>
    <td>Lorem</td>
    <td>Ipsum</td>
  </tr>
  <tr>
    <td>Text</td>
    <td>MoreText</td>
    <td>Lorem</td>
    <td>Ipsum</td>
  </tr>
  <tr>
    <td>Text</td>
    <td>MoreText</td>
    <td>Lorem</td>
    <td>Ipsum</td>
  </tr>
  <tr>
    <td>Text</td>
    <td>MoreText</td>
    <td>Lorem</td>
    <td>Ipsum</td>
  </tr>
</table>

There are many ways to do what you're after, however a robust and extensible way would be to get the property names from the table header row, then get the values from the row that was clicked on.

I don't know why you have hidden cells in the header, it just plicates things. If you're using it for data, that would be much better in an associated object or data-* property of the table or row.

function getRowDetails(event) {
  row = this;
  var table = row.parentNode.parentNode;
  var header = table.rows[0];
  
  // Get property names from header cells
  var props = [].reduce.call(header.cells, function(acc, cell ) {
    if (!cell.hasAttribute('hidden')) {
      acc.push(cell.textContent);
    }
    return acc;
  }, []);
  
  // Get value for each prop from data cell clicked on
  var result = props.reduce(function(acc, prop, i) {
    acc[prop] = row.cells[i].textContent;
    return acc;
  }, {});
  
  // Do something with result
  console.log(result);
  return result;
}

// Add listener to body rows, could also put single listener on table
// and use event.target to find row
window.onload = function() {
  [].forEach.call(document.getElementsByTagName('tr'), function(row, i) {
    if (i) row.addEventListener('click', getRowDetails, false);
  });
}
<table align="center" id="tableID" border="1">
<thead>
  <tr><th hidden="hidden"></th><th>name</th><th>age</th></tr>
</thead>
<tbody style="cursor: pointer;">
  <tr><td >Clark</td><td>29</td></tr>
  <tr><td >Bruce</td><td>30</td></tr>
</tbody>
</table>

发布评论

评论列表(0)

  1. 暂无评论