views:

35

answers:

2

I have a UserControl in MVC which may be repeated many times on the page.

Say I had something like the following:

<div>
    <a href="#" class="enableTextBox">edit</a>"
    <input type="text" class="comments" readonly="readonly" />
</div>

<div>
    <a href="#" class="enableTextBox">edit</a>"
    <input type="text" class="comments" readonly="readonly" />
</div>

<div>
    <a href="#" class="enableTextBox">edit</a>"
    <input type="text" class="comments" readonly="readonly" />
</div>

How can I find the class="comments" element which is in the same div as the class="enableTextBox" link, in the onclick event of the link?

Is this a sensible way of handling element Id conflicts? Is there a better way? How secure would it be in terms of running in an enterprise app and being certain of data consistency?

+2  A: 

Using jQuery's .siblings() method is one way:

$('.enableTextBox').click(function() {
    var $comments = $(this).siblings('.comments');
    return false;  // Prevent page refresh
});

There are lots of traversal methods available in jQuery:

EDIT: Added return false; to prevent the link from refreshing the page.

Here's an example you can test: http://jsfiddle.net/MZEmP/

patrick dw
+1  A: 
$(".enableTextBox").click(function() {
   $(".comments", $(this).parent())  //this will get you the comments associated with the anchor you click on
})
John Hartsock