fpiliego
fpiliego

Reputation: 35

How to get a textarea parent with jQuery

I have this situation:

<div class='postit_popup' id='xxx'>
   <div style='margin-left:20px;margin-top:20px;text-align:justify;'>
      <textarea class'txtNota'>some text</textarea>
   </div>
   <div class='clear'></div>
   <div style='margin-left:20px;' align='left'>
      <img class='okNota' src='img/ico/task-completed.png' height='20' width='20'>&nbsp;
      <img class='cancewlNota' src='img/ico/button_cancel.png' height='20' width='20'>
   </div>
</div>

I need to get content in the textarea when there is a click on the image with class "okNota".

I did it in this way:

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

   var obj = $(this).parent().parent();

   alert(obj.children(0).children(0).val());
});

But I need to know if there is another way to obtain it.

Thank you very much.

Upvotes: 1

Views: 3048

Answers (4)

Darm
Darm

Reputation: 5659

Use:

$(this).closest(".postit_popup").find("textarea").val();

Upvotes: 0

dku.rajkumar
dku.rajkumar

Reputation: 18588

$(".okNota").click( function() {     
var value = $('.txtNota').val();
 }); 

This will work. You are missing '='.

<textarea class = 'txtNota'>some text</textarea> 

Upvotes: 0

Shomz
Shomz

Reputation: 37711

Does this help: http://jsfiddle.net/vgtQR/

EDIT (for JohnP)

HTML

<div class='postit_popup' id='xxx'>
   <div style='margin-left:20px;margin-top:20px;text-align:justify;'>
      <textarea class='txtNota'>some text</textarea>
   </div>
   <div class='clear'></div>
   <div style='margin-left:20px;' align='left'>
       <div class='okNota'>OK Image</div>
   </div>
</div>

JS

$('.okNota').click( function() {
   alert($('.txtNota').val());
});

Upvotes: 0

betamax
betamax

Reputation: 14061

Try:

$(this).parents(".postit_popup").find("textarea").val();

Or if you have more than one textarea in .postit_popup then use:

$(this).parents(".postit_popup").find(".txtNota").val();

What this does is traverse up the DOM from .okNota until .postit_popup is found and then it goes back down the DOM to find a textarea or an element with the .txtNota class.

Upvotes: 4

Related Questions