I am testing to set up an “button event listener” that would show a hidden div at button click. Below code works, my question is more if there are other ways of solving this, with only HTML/CSS and PHP ?
I am fully aware the “button event listener” in this particular case is more of a “superglobal $_POST variable” checker.
The purpose of the test was more to see if the button press can be scanned from PHP itself (skipping other logics such as JS or jquery, etc).
<!DOCTYPE html> <html lang="en"> <head> <title>Test</title> </head> <body> <!-- Styling --> <style> .myDiv {display:none;} </style> <!-- Form --> <form method="post"> <button type="submit" name="button">Show div</button> </form> <div class="myDiv">MyDiv text...</div> <pre> <?php // Logics // Button event listener print_r($_POST); if(isset($_POST['button'])) { echo "You pressed the button!"; echo "<style> .myDiv {display:block} <style>"; } ?> </body> </html>
Advertisement
Answer
first check if is post request and do visibility with php variable:
<!DOCTYPE html> <html lang="en"> <head> <title>Test</title> </head> <body> <?php $display = 'none'; if(!empty($_POST)) { if(array_key_exists('button', $_POST)) { $display = 'block'; } } ?> <style> .myDiv {display:<?php echo $display;?>;} </style> <!-- Styling --> <!-- Form --> <form method="post"> <button type="submit" name="button">Show div</button> </form> <div class="myDiv">MyDiv text...</div> <pre> <?php print_r($_POST); // Logics // Button event listener ?> </body> </html>