First, I'm new to form and looking forward to all your insight.
My issue: I'm building a small site and I've run into a problem generating unique HTML ids. I'm generating the HTML via a loop in PHP, sent to a smarty template. I admit, my JavaScript abilities are not good which is why I can't figure this out… All I want to is to display the comment form under each article when the "add a Comment" link is clicked.
Here is the JavaScript -
<script>
function show_cform() {
o = document.getElementById("comment_link");
if (o) { o.style.display = ""; }
o = document.getElementById("comment_form");
if (o) { o.style.display = "none"; }
}
</script>
And the HTML that repeats several times -
<div id="comment_form">
<!-- Article Content Here -->
<a href="javascript:show_cform();">Add a Comment</a>
</div>
<div id="comment_link" style="display: none;">
<form method="post" action="blog_comment.php">
<input type="hidden" name="ID" value="{$id}">
Your Name:<br />
<input name="name" type="text" />
<br /><br />
Comment:<br />
<textarea name="comment" rows="8" cols="40"></textarea>
<br /><br />
<input type="submit" value="Post comment">
</form>
</div>
Thanks in advance for the help!
I would do something like this (CORRECTED):
<script>
function show_cform(formDiv) {
// We pass the container into the function, so we can work out the rest
var parts, idNum;
// Get the number from the id
parts = formDiv.id.split('_');
idNum = parts[parts.length -1];
// Change the display of the elements
formDiv.style.display = "none";
document.getElementById("comment_link_"+idNum).style.display = "block";
}
</script>
...and...
<?php
// Presumably you are generating this in a loop. I don't know how
// your loop currently works, but you just need an incrementing
// id that is unique to each iteration, and put it onto the end
// of the id's of the elements
// For example
for ($i = 0; ($someCondition); $i++) {
?>
<div id="comment_form_<?php echo $i; ?>">
<!-- Article Content Here -->
<a href="javascript:show_cform(this.parentNode);">Add a Comment</a>
</div>
<div id="comment_link_<?php echo $i; ?>" style="display: none;">
<!-- etc etc -->
<?php } ?>
Actually, that's nothing like what I'd do - but working with what you have that is what I'd do. I don't have the time to explain exactly how I'd handle it at the moment, but I may edit this answer when I don't have a crying baby to deal with...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With