I am trying to pass $post; a variable created in a mysql query, to javascript function showDiv. Currently this doesnt work.
$post = $row['id'];
?>
<script type="text/javascript">
function showDiv() {
var note = "<?php echo $post ?>";
document.getElementById("<?php echo $post; ?>").style.display = "inline";
}
</script>
<?php
$addnote = '<input type="button" value="addnote" onclick="showDiv()"><div id="'.$postid.'" style="display:none;" class="'.$postid.'"> WELCOME</div>';
But if I change $post
to have a html value e.g
$post = '11';
then this code works.
I am novice in javascript so please be gentle, Any help is greatly appreciated. Thank you.
check your $row['id'] if it's returning something.
<?php echo $row['id']; ?>
or check your source code. your code might look something like
<script type="text/javascript">
function showDiv() {
var note = "";
document.getElementById("").style.display = "inline";
}
</script>
If you are in a loop, I think JS doesn't like redeclare your function "showDiv()". Try this :
$post = $row['id'];
$addnote = '<input type="button" value="addnote" onclick="showDiv('.$post.')"><div id="'.$post.'" style="display:none;" class="'.$post.'"> WELCOME</div>';
And the javascript NOT in the loop :
<script type="text/javascript">
function showDiv(note) {
document.getElementById(note).style.display = "inline";
}
</script>
Assuming that: $post = $row['id']
has a value. You want var note
to have a value of a string. JS wraps strings in single or double quotes. so wrap <?php echo $post ?>
in a string like this:
var note = "'"+<?php echo $post ?>"'";
This will prepend and append the quotes around the $post value so that JS can recognize it as a string.