0

Hello all, newbie here with a, hopfully, easy question. I'm creating a simple site for personal use for family photos and things and I am having troable with my onclick only working once. I've searched the web bu found no answer that has solved my issue. I've stripped my code to bare minimum just to test the on click and still will only work once. Any help would be greatly appreciated.

<?PHP

$number = 1;

?>
<HTML>
<HEAD>

<script Type="Text/javascript">

function add()
{
<?php 
$number += 2;
?>
document.getElementById("test").innerHTML = "<?PHP echo $number; ?>";

}

</script>

</HEAD>
<BODY>

<Table><TR><TD><button onclick="add();">CLICK</button><P id="test">One</P></TD></TR></Table>


</BODY>
</HTML>
2
Contributors
2
Replies
3
Views
4 Years
Discussion Span
Last Post by jeepdude
0

PHP is run by the server prior to passing everything to the browser which processes JavaScript. Once this code gets to your browser it will look like this:

<HTML>
<HEAD>

<script Type="Text/javascript">

function add()
{

document.getElementById("test").innerHTML = "3";

}

</script>

</HEAD>
<BODY>

<Table><TR><TD><button onclick="add();">CLICK</button><P id="test">One</P></TD></TR></Table>


</BODY>
</HTML>

So it doesn't metter how many times you click the button it will always just output what ever the number was when the server processed your PHP. Best bet in this situation would be to transfer your number to JS than do any processing.

<?PHP

$number = 1;

?>
<HTML>
<HEAD>

<script Type="Text/javascript">

var number = <?php echo $number; ?>;

function add()
{
number = number + 2;
document.getElementById("test").innerHTML = number;
}

</script>

</HEAD>
<BODY>

<Table><TR><TD><button onclick="add();">CLICK</button><P id="test">One</P></TD></TR></Table>


</BODY>
</HTML>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.