I've already searched for different ways to do this but no luck with fixing my problem. My code looks basically like this:
<?php
$attnum = 1;
?>
<button type="button" onClick="<?php $attnum++ ?>">+</button>
<h3><em>att<?php echo "$attnum" ?>: </em></h3>
When the page loads it have already added 1 on $attnum. I only want to add on $attnum when the button is pressed. What have I done wrong?
If you want to do it server side, you can do it like this:
<?php
session_start();
// Page was not reloaded via a button press
if (!isset($_POST['add'])) {
$_SESSION['attnum'] = 1; // Reset counter
}
?>
<form method='post'>
<input name='add' type="submit" value='+'>
<h3><em>att<?php echo $_SESSION['attnum']++ ?>: </em></h3>
</form>
If you want to do it client side, do it like this:
<button id='add' type="button">+</button>
<h3><em>att<span id='val'>1</span>: </em></h3>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('add').addEventListener('click', function() {
document.getElementById('val').innerHTML++;
});
});
</script>