Search code examples
javascriptjquerytraversal

jQuery traversing get variable value from cell


I've got an HTML table like:

<table id="realtime" class="table table-bordered table-hover">
<tr>
<th>Agent</th>
<th>Number</th>
</tr>
<tbody><tr class="rowid">
<td class="name">Joe</td>
<td class="extension">Agent/1701</td>
<td><button onclick="myCall()" class="btn btn-default btn-sm">Record</button>
</td></tr>
<tr class="rowid">
<td class="name">Jane</td><td class="extension">sip/1702</td>
<td><button onclick="myCall()" class="btn btn-default btn-sm">Record</button></td>
</tr></tbody></table>

And a javascript:

     function myCall() {
       var table = $('#realtime').dataTable(); 
       var extension = $('*').closest('td.extension').text();
       alert(extension);
     }

Which displays the extensions like: Agent/1701 Agent/1702

I want to be able to get the individual values assigned to the extension variable So, that when the onclick fires, I can send the extension variable to a POST function. For the agent in that row only. Tried several different ways, like:

var extension = $(this).closest('tr.rowid').find('td.name').text();

But, I just can't get it to work.

Any suggestions?


Solution

  • try

    HTML

     <button onclick="myCall(this)"
    

    JS

     function myCall(elm) {
               var extension = $(elm).closest("tr").find('td.extension').text();
               alert(extension);
             }
    

    or

    $("button").click(function(){
           var extension = $(this).closest("tr").find('td.extension').text();
           alert(extension);
    });
    

    DEMO