Steve Steve - 2 months ago 9
HTML Question

value of textarea in loop

html and php:

foreach($questions as $question)
{
?><br><textarea class="answer">Answer here...</textarea><button data-id="<?php echo $question->id;?>"class="addanswer">Post</button><?php
}


jquery:

$(document).on('click','.addanswer',function(e)
{
e.preventDefault();
var answer=$('textarea.answer').val();
var q_id=$(this).data('id');
alert(answer);
alert(q_id);


I got the text i enter in the textarea for first question. For all other questions it only alerts Answer here... even though i got the expected q_id.

Answer

This is your problem:

var answer=$('textarea.answer').val();

This will always give your the value of the first $('textarea.answer') element that jQuery encounters; it not linked to the clicked button in any way.

You want the value of the element next to the button you clicked, so with this html structure, you could use:

var answer = $(this).prev().val();