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>

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>

ahh... true, didn't catch that - thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.