views:

142

answers:

3

I have a quite easy jquery question that I can't get right, when clicking on a link I need to insert some text in the right p (the table row before).

This is the html:

<table>
<tr>
    <td>
        <p class='MyClass'>NOT HERE</p>
    </td>
</tr>
<tr>
    <td>
        <p class='MyClass'>NOT HERE</p>
    </td>
</tr>
.
. //Many table rows
.
<tr>
    <td>
        <p class='MyClass'>HERE I WANT TO INSERT THE TEXT</p>
    </td>
</tr>
<tr>
    <td>
        <div>
             <a href='#' class='MyLink'>insert text</a>
        </div>
    </td>
</tr>
</table>

This is the jquery:

$('.MyLink').click(function() {
    HOW CAN I MAKE SOME TEXT GO INTO THE RIGHT <p> HERE?
});
+1  A: 
$(this).closest('tr').prev('tr').find('.myClass').html('text here');

(untested)

just somebody
Just a note: closest() is new in jQuery 1.3, you probably need to do some more element traversal if you can't use the new version.
Jay Zeng
A: 

One real easy way would be to give:

<p class='MyClass'>HERE I WANT TO INSERT THE TEXT</p>

a class or ID, so that you could reference it directly. For instance:

<p id="insertHere" class='MyClass'>HERE I WANT TO INSERT THE TEXT</p>

Then you could just do something like:

$('.MyLink').click(function() {
    $("#insertHere").text($("#insertHere").text() + "SOME TEXT YOU WANT TO INSERT");
});

If you want to specify the "insert into" P some other way, just change the selector from "#insertHere" to one that defines which P you want to insert in to.

Also, I think:

$('.MyLink').click(function() {
    $("#insertHere").append("SOME TEXT YOU WANT TO INSERT");
});

will work too (and be shorter), but I'm not 100% certain (so test first).

machineghost
A: 
$(this).parents('tr:first').prev('tr').find('.myClass').html("The Text that you want");

.parents walks up the dom to the first tr above your link, then prev('tr') takes you to the previous row, and finally the find searches down the tr for all elements that have the ".myClass" class.

Kevin W Lee