digitaltos
digitaltos

Reputation: 85

Get the value of a table cell in javascript with external script

I have a simple table filled with rows from a MySQL database, the HTML part looks like this

  <tbody>
    <?php while($row = mysqli_fetch_row($result)){ ?>
    <tr class="rows" id="<?php echo $row[0]; ?>">  // the id is an auto incremented int
      <td id="col1"><?php echo $row[1]; ?></td>
      <td id="col2"><?php echo $row[2]; ?></td>
      <td id="col3"><?php echo $row[3]; ?></td>
      <td id="col4"><?php echo $row[4]; ?></td>
      <td id="col5"><?php echo $row[5]; ?></td>
    </tr>
    <?php } ?>
  </tbody>

It gets the job done and I have a nice table. Now I want that if I click on a row, i get five variables with the values of the cells.

The problem what stopped me was to get the <td> element. This is what I tried in the external javascript file:

var rows    = document.getElementsByClassName('rows');
for (var i=0; i<rows.length; i++){
    rows[i].onclick = function(){
        console.log(this.getElementById('col1')); // I tried to print it first
    }
}

The console responded this: Uncaught TypeError: undefined is not a function.

Then I tried console.log(rows[i].getElementById(vonalkod));, but it responded Uncaught TypeError: Cannot read property 'getElementById' of undefined

If I only write console.log(this); then it prints what I expect, the whole row in html.

So my question is that what is the syntax to get those cells by ID?

Upvotes: 0

Views: 1515

Answers (2)

Alessandro
Alessandro

Reputation: 1453

It doesn't work because the object this is a HTMLTableRowElement (see http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/html2/HTMLTableRowElement.html)

Here a library as jQuery comes very handy. Your script written using jQuery is as easy as

jQuery('.rows').click(function(){
    alert(jQuery(this).children('#col1').text());
});

Upvotes: 1

blgt
blgt

Reputation: 8205

What you can do to get the contents of a cell is

document.getElementById('col1').innerHTML

Now, having said that, it will only work if you have ONE col1: if you have more than one of these <tr>s each will have five tds like <td id=col1>, the same for the rest of the id-s. That's invalid HTML. Consider replacing those id-s with classes, or with additional PHP.


Or, better yet, you can forgo all these clumsy id-s entirely and use something like:

rows[i].onclick = function() {
    console.log(this.childNodes[0].innerHTML); // col1
    console.log(this.childNodes[1].innerHTML); // col2
    // ... etc
}

Upvotes: 1

Related Questions