tags:

views:

38

answers:

4

Hi,

I have a table that is generated dynamically. And a click event on a button in one of the rows. I need to get the values of the labels with classes 'label1' and 'label2' in the row that the button is clicked. here is example html:

<table>
<tbody>
    <tr>
        <td><label class="label1">test row 1 - label 1</label></td>
        <td><label class="label2">test row 1 - label 2</label></td>
        <td><input type="button" id="btnTest1" class='btn' value="Click me" /></td>
    </tr>
    <tr>
        <td><label class="label1">test row 2 - label 1</label></td>
        <td><label class="label2">test row 2 - label 2</label></td>
        <td><input type="button" id="btnTest2" class='btn' value="Click me" /></td>
    </tr>
</tbody>
</table>

I can get the parent row by doing this: $(this).closest('tr') but then How do I chain that to get the 2 labels in the row thats clicked?

A: 

You're looking for all the children of the current <tr> except for the last one:

$(this).parent().parent().children(':not(:last)')

Final EDIT:

$(this).closest('tr').children(':not(:last)').children('label')
Rixius
This won't give you the labels.
patrick dw
fixed that >.< my mistake
Rixius
what's the `children(':not(:last)')` for, just `$(this).closest('tr').children('label')` would be the same, but shorter and more readable
jigfox
wouldn't `.children('label')` from the `<tr>` choke since the '<label's aren't direct descendants? However, `$(this).closest('tr').find('label')` is a much better idea.
Rixius
+1  A: 

To get the labels, do this:

$(this).closest('tr').find('label');

Not sure what you mean by the values of the labels, but if you want the text of the labels in an array, you can do this:

var array = $(this).closest('tr').find('label').map(function() {
    return $(this).text();
}).get();
patrick dw
`$(this).closest('tr').find('input');` is the same as just `$(this)` because the only input is the button that gets clicked
jigfox
@Jens - Yes, I mistyped `input` instead of `label`.
patrick dw
Yes, much better. ;-)
jigfox
+1  A: 
$(this).closest('tr').find('.label1, .label2');

or if you're sure, there won't be any unneeded labels:

$(this).closest('tr').find('label');
jigfox
This won't work.
patrick dw
now it will work
jigfox
Yes, much better.
patrick dw
I like your most recent update the best. Looks familiar. I wonder why... ;o)
patrick dw
A: 
$(this).parent().parent().find('.label1').html()

Would give you the value of the string content in the label1 class. Depending on what you want to do you may end up iterating through something more like this:

$(this).parent().parent().find('.label1,.label2').each()
HurnsMobile
`$(this).parent()` will return the `<td>` and not the `<tr>` and thus there won't be any labels found
jigfox
Thanks for pointing that out Jens. Corrected the sample code.
HurnsMobile