How do I differentiate between elements inside a table that is populated using a loop? So that when I use Javascript to show an element on click, it will show the correct element?
Currently, when I click comment, it just shows the first item, and then the rest of the rows don't work.
When the user clicks the comment button, I want a textarea to appear. The problem is that since it is a table, how do i make it so each comment button in the table shows the box within its table. do i need to add an incrementing id to each row in the table?
Here is the Javascript:
$('#postcomment').click(function(){
$('#comment_text').css('display','inline');
})
Here is the PHP:
<table>
<?php
foreach ($posts as $key => $list){
echo "<tr>";
echo "<td>
<a id='postcomment'>Comment</a>
<textarea id='comment_text' style='display:none;placeholder='Type your comment.'></textarea>
</td>";
echo "</tr>";
}
?>
</table>
Is the best solution for this, to give each row a unique id, and how would I do this? Also, how would I then call the Javascript to work for each unique id?
id
s must be unique within a document. Instead use a class. Once you do that, you can use things such as parent
, siblings
, find
, etc. to find the appropriate element based on the location of the one you clicked.
Something like this:
$('.postcomment').click(function(){
$(this).next('.comment_text').css('display','inline');
});