jQuery(document).ready(function($) {
$('.save_caption').live("click", function() {
alert($(this).closest('.caption_text').find('.caption_textarea').val());
});
});
How do I get the value of this textarea jquery
-
01-06-2022 - |
Question
I am trying to get the value of the textarea (class="caption_textarea") when clicked on the link with class "save_caption".
The value of the textarea is changed with ajax and I am not including that here and therefore it is not always empty.
I have following HTML code:
<div class="caption_text" style="display:none;">
<div class="small_icons">
<a href="#" onclick="return false;" class="save_caption"><img src="<?php echo base_url('public/images/tick.png'); ?>"/></a>
<a href=""><img src="<?php echo base_url('public/images/delete.png'); ?>"/></a>
</div>
<textarea id="<?php echo $image_name_without_path[0]; ?>" class="caption_textarea" cols="32" rows="2" name="caption_text"></textarea>
</div>
I tried jquery's next, closest and find methods but I am unable to retrieve the value of the closest textfield's value to the a element clicked. Jquery code below:
jQuery(document).ready(function($) {
$('.save_caption').live("click", function() {
alert($(this).closest('textarea').find('.caption_textarea').val());
});
});
Solution
OTHER TIPS
You can find the cpmmon parent caption_text
using .closest() then find the textarea inside it using .find()
jQuery(document).ready(function($) {
$('.save_caption').live("click", function() {
alert($(this).closest('.caption_text').find('.caption_textarea').val());
});
});
closest() looks for the closes ancestor. You might want to try next() or nextAll()
jQuery(document).ready(function($) {
$('.save_caption').live("click", function() {
alert($(this).next('textarea.caption_textarea').val());
});
})
or something similar should work fine.
Change the selector a bit. First take parent of .save_caption then look for its siblings having .caption_textarea class. Your code is a bit modified below -
jQuery(document).ready(function($) {
$('.save_caption').live("click", function() {
alert($(this).parent().siblings('.caption_textarea').val());
});
});
Hope it will work.
Why are you using closest? I'm possibly missing some detail of your code. Either way, wouldn't the solution be:
alert($('.mytextarea').val());
Or:
alert($('.mytextarea').html());
If your problem is that the class isn't unique to that text area (I would use an id but that's up to you), try:
alert($(this).next().val());
You can use 'textarea.mytextarea' to keep it strictly to textareas or .next('textarea').
Corrections and editions are welcome.
ps: make sure "this" is giving you the correct element.