I'm trying to write a function that will dynamically display a form (inside a div, of which there will be several instances, thus the weird "id" name) when you click a button. Then, it should POST to a separate PHP file. Here's the code I have so far:
function add_comment_url($table, $id) {
$html = '<div id="comment' . $id . '" name="comment_box" style="display: none">
<form action="cgi-bin/add_comment.php" method="post">
<textarea id="comment" name="comment"></textarea>
<input type="hidden" name="id" value="' . $id . '">
<input type="hidden" name="table" value="' . $table . '">
<input type="submit" name="submit" value="Submit Comment">
</form></div>
<input type="button" value="Add Comment" onclick="showComment();">
<script>
var id= ' . json_encode($id) . ';
showComment(id);
</script>';
return($html);
}
The "Add Comment" button shows up fine, but I can't get the to display, and the Firefox console shows a "TypeError: div is null" error when I click on the button.
I'm guessing I screwed up the JS variable assignment, but I'm at a loss as to how to fix it. Any thoughts?
EDIT - Final code
I figured out what I did wrong... I was defining the var
when I didn't need to! Here's the new function, which works:
function add_comment_url($table, $id) {
$html = '<div id="comment' . $id . '" name="comment_box" style="display: none">
<form action="cgi-bin/add_comment.php" method="post">
<textarea id="comment" name="comment"></textarea>
<input type="hidden" name="id" value="' . $id . '">
<input type="hidden" name="table" value="' . $table . '">
<input type="submit" name="submit" value="Submit Comment">
</form></div>
<input type="button" value="Add Comment" onclick="showComment(' . $id . ');">';
return($html);
}
You can't use <?php
inside PHP strings. You should use string concatenation or interpolation:
function add_comment_url($table, $id) {
$html = '<div id="comment' . $id . '" name="comment_box" style="display: none">
<form action="cgi-bin/add_comment.php" method="post">
<textarea id="comment" name="comment"></textarea>
<input type="hidden" name="id" value="' . $id . '">
<input type="hidden" name="table" value="' . $table . '">
<input type="submit" name="submit" value="Submit Comment">
</form></div>
<input type="button" value="Add Comment" onclick="showComment();">
<script>
function showComment() {
var id= ' . json_encode($id) . ';
div = document.getElementById(\'comment\' + id);
div.style.display = "block";}</script>';
return($html);
}
Are you repeating this function definition for every comment block? I would recommend just defining showComment()
once, and make it take the commentID
as an argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.