views:

43

answers:

3

How do I select an element with jquery, when a different element is clicked, when you don't know the name of the element? The code below is looping over the all the categories. I don't know how many categories there are, or what the names will be. When the 'insertUrl' link is clicked, I need to select the text area.

The only thing I can thinking is running an function in onclick and passing the name of the text area as a parameter.

Also, I'm not sure that I can use a selector when every link has the same id, so is this even possible?

<%
    FullName = objCategory.ID & "|" & objCategory.Name
%>      
<TD COLSPAN="2">
<TEXTAREA ROWS="5" CLASS="formWide" id="<%=FullName %>"><%= objCategory.Text %></TEXTAREA><br />
<a href="#" id="insertUrl">Insert URL</a>
</TD>
+1  A: 

If the HTML structure stays the same you can use .prev()

You shouldn't have elements with the same ID. You can use classes class="insertUrl"

<%
  FullName = objCategory.ID & "|" & objCategory.Name
%>      
<TD COLSPAN="2">
  <TEXTAREA ROWS="5" CLASS="formWide" id="<%=FullName %>"><%= objCategory.Text %></TEXTAREA><br />
  <a href="#" class="insertUrl">Insert URL</a>
</TD>

and

$(".insertUrl").click(function() {
  var textarea = $(this).siblings('textarea');
});
mr.moses
$(this).prev().prev(); works because of the <br>. is that bad practice, or is there a better way?
pinniger
changed to use $(this).siblings('textarea'); as TeKapa suggested
mr.moses
+1  A: 

maybe its better if you use:

$(this).siblings('textarea');

this way you have more flexibility with the html controls order. this way, if you remove the
or change something else inside that TD the script will still works.

TeKapa
+1  A: 

An even better way would be to use the <label> element. This way, you can insert later additional elements between the text comment and the textarea, and it still will work.

<textarea id="ta_id1" onclick="click_processing_func"></textarea>
<label for="ta_id1" class="link">Insert Url</label>

Now, if anyone clicks on the label, textarea will receive the click event.

David Parunakian