BAD_SEED
BAD_SEED

Reputation: 5056

jQuery: get value of clicked element

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?

Upvotes: 3

Views: 43547

Answers (4)

Ghulam Dastgeer
Ghulam Dastgeer

Reputation: 187

  $(function () {
        $(".Cartbtn").click(function () {
            var temp = {
                "Id": $(this).data("itemid"),
                "Name": $(this).data("itemname"),
                "Price": $(this).data("itemprice"),
                "Quantity": $(this).data("itemqty"),
                "ImageUrl": $(this).data("itemimgurl"),
            });

Upvotes: 1

Wiks
Wiks

Reputation: 11

$(document).bind("click", function (e) {
    $(e.target).closest("li").toggleClass("highlight");
    alert($(event.target).text());
});

this will directly give you the selected element id. $(event.target).text(); will give you the selected element text within a second.

Upvotes: 0

Dhanasekar Murugesan
Dhanasekar Murugesan

Reputation: 3229

try this:

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

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

alert(clickedValue );    

});

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

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

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:

Upvotes: 15

Related Questions