I am having a table td which contains a textarea and a button and I want to send the value of textarea on button click via AJAX however there is a problem selecting the closest textarea to the button.
JavaScript
$(document).ready(function () {
$(document).on("click", ".addR", function () {
paperID = $(this).attr("paperID");
commentID = $(this).attr("commentID");
text = $(this).closest("textarea").val();
$.ajax({
data: {
paperID: paperID,
commentID: commentID,
text: text
},
type: 'POST',
url: 'add_rebuttal.php',
success: function (response) {
alert(response);
window.location.href = window.location.href;
}
});
});
});
PHP:
while ($row = mysql_fetch_assoc($comments)) {
echo "<tr><td>{$row['text']}</td>";
?>
<td><br /><textarea class="reText" rows='5' name='reText' id='reText' style='width:98%;' type='text'></textarea>
<button commentID="<?php echo $row['comment_id'] ?>" paperID="<?php echo $paper_id ?>" class="addR" type="button" name="addR" id="addR">send rebuttal</button></td></tr> <?
}
The problem is $(this).closest("textarea").val(); return undefined, so how I can solve this problem?
closest() returns the closest ancestor. Your textarea is not an ancestor of your button, it’s a previous sibling. Instead, try: