JohnSmith
JohnSmith

Reputation: 1557

How do I associate an ID with a content of a div?

For example I have a HTML table...

name | grade  | action
bob  | 1.0    | [button class="button" id='1']
jack | 2.0    | [button class="button" id='2']
john | 3.0    | [button class="button" id='3']

When I click the button,

to get the id...

$(function(){
$('.button').click(function()
var buttonid = this.id
});
});

so if I were to press buttonid 1 how do I get the name 'bob' without having to open the database?

Additionally if I press the button how do I get the values in each column? i.e. If I press button 3 how do I get grade 3.0 or get both name and grade?

Script that generates the row of the table

while(){ 
echo '<tr>'; 
echo '<td>'.$name.'</td>'; 
echo '<td>'.$grade.'</td>'; 
echo '<td> <input type="button" class="button" id="'.$id'"</td>';
echo '</tr>';
}

Upvotes: 1

Views: 230

Answers (4)

voigtan
voigtan

Reputation: 9031

The most simplest way (in my meaning) is to use the HTML-data attributes on maybe your TR element and have all that data there, then you could just use $(this).closest("tr").data("name"); like:

<tr data-name="bob" data-grade="1.0">
    <!-- all your td-elements -->
</tr>
<tr data-name="jack" data-grade="2.0">
    <!-- all your td-elements -->
</tr>

Upvotes: 3

rickyduck
rickyduck

Reputation: 4084

Your js should be:

$(function(){
    $('button').click(function(){
        var text= $(this).parent().siblings('td:first').text();
    });
});

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92943

Try:

$(function() {
    $('button').click(function() {
        var name = $(this).closest('tr').children().first().text();
        // do something with 'name'
    });
});

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359896

You question is a bit unclear but I think this is roughly what you're looking for:

$('#myTable button').click(function ()
{
    var $tr = $(this).closest('tr'),
        $nameTd = $tr.children('td:first'),
        name = $nameTd.text();

    alert(name);
});

Demo: http://jsfiddle.net/mattball/7XV96/

Upvotes: 3

Related Questions