Steve Steve - 11 months ago 42
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


var answer=$('textarea.answer').val();
var q_id=$(this).data('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 Source

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();