stackato
stackato

Reputation: 1145

HTML/JS -- get clicked row

I have a table where each row has a hyperlink. When the link is clicked, a URL to aggregate data will be called. I need to pass the clicked row/record to this URL but unsure of how to get the clicked row.

Here's some sample code

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td><a href="#" onclick="aggregate()">Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td><a href="#" onclick="aggregate()">Eve</a></td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
</table>

<script>
    function aggregate(){
       //get clicked row, pass as parameter 
    };
</script>

Do I instead need to wrap each row in a form and do a form submit?

Thanks

Upvotes: 0

Views: 86

Answers (4)

Aniruddha Das
Aniruddha Das

Reputation: 21698

You can put id to all table data and the access the <td> using your javascript program.

<td id='record-1'><a htef="...?row=record-1">link</a><td>


<script>

function tty() {

  document.getElementById('record-1').
  // do what ever you want to do this your row
}

Upvotes: 0

relic
relic

Reputation: 1704

Think this should do it. Grabs the element that was clicked, and iterates through each parent until the tagname matches and returns that match as the row var.

function aggregate(ev){
    var el = ev.currentTarget,
        row = (function() {
            while ((el = el.parentElement) && !el.tagName === 'tr');
            return el;
        })();

    // Do stuff with "row" ....
}

Upvotes: 1

Vaibhav Singh
Vaibhav Singh

Reputation: 942

In your function pass the event and check the target of the event.

http://api.jquery.com/event.target/

 <!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript">
      function check_me(event) {
        event.preventDefault();
        alert("Hello World!")
      }
    </script>
  </head>
  <body>
    <a  onclick="check_me(event);">Click Me!</button>
  </body>
</html>

Upvotes: 0

jafarbtech
jafarbtech

Reputation: 7025

Pass this to the function to get the row by using t.parentNode.parentNode and perform some action on it

<td><a href="#" onclick="aggregate(this)">Jill</td>

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td><a href="#" onclick="aggregate(this)">Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td><a href="#" onclick="aggregate(this)">Eve</a></td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
</table>

<script>
    function aggregate(t){
       //get clicked row, pass as parameter 
      t.parentNode.parentNode.remove();
    };
</script>

Upvotes: 3

Related Questions