Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: get value of clicked element

Tags:

jquery

I have this piece of code:

<tr class="editField">
  <td>abc</td>
  <td>123</td>
  </td>
</tr>
<tr class="editField">
  <td>dfg</td>
  <td>456</td>
  </td>
</tr>

And then I have this javascript to open a dialog with jQuery:

$( ".editField" ).click(function() {
        alert(...); // should get me 123
});

Suppose I click on first tr and I would get the content of second td (i.e 123), what should I write?

like image 239
BAD_SEED Avatar asked Feb 03 '26 22:02

BAD_SEED


2 Answers

I'd suggest, given your current mark-up:

$( ".editField" ).click(function() {
        alert($(this).find('td:eq(1)').text());
});

But, while this works in the given example, it'd be much easier (and subsequently far more reliable) to add some defining attribute to the element from which you wish to recover the 'value', such as the class-name 'value', giving HTML like so:

<tr class="editField">
  <td>abc</td>
  <td class="value">123</td>
</tr>

And the jQuery:

$( ".editField" ).click(function() {
        alert($(this).find('td.value').text());
});

Or, of course, if the 'value' will always be the last td element of any given row (of the relevant class), then you could instead use:

$( ".editField" ).click(function() {
        alert($(this).find('td:last').text());
});

Incidentally, please note that your HTML is malformed, you have a surplus </td> after the last cell in both rows of your sample code.

References:

  • eq() selector.
  • find().
  • :last selector.
  • text().
like image 110
David Thomas Avatar answered Feb 06 '26 12:02

David Thomas


try this:

$( ".editField" ).click(function() {

    var clickedValue = $(this).find('td:first').next().text();

alert(clickedValue );    

});

fiddle link : http://jsfiddle.net/9cRRj/8/

like image 27
Dhanasekar Avatar answered Feb 06 '26 10:02

Dhanasekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!