I'm pretty new with PHP, so help please.
I need a web page in php with a checkbox. That page should refresh itself each time I do an action to the checkbox (so for both check or uncheck). Once it’s refreshed the page should keep the latest value of the checkbox.
I tried the following example modifying another code I took from StackOverflow, but it doesn’t works as I wish.
Any suggestion?
<?php
session_start();
$checked = "";
if($_SESSION['myaction'] != $_SESSION['value'])
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
echo ":(";
}
$_SESSION['myaction'] = $_SESSION['value'];
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
echo "checked='checked'";
}
$myaction = 2;
print ">";
?>
</form>
My Answer:
You can achieve this by using JavaScript to detect when the checkbox is checked or unchecked and then trigger a page refresh. Here's an example code snippet that you can use:
html
Refresh Page on Checkbox Change
In this code, we have a checkbox element with the id "myCheckbox" and an onchange event listener that calls the refreshPage() function whenever the checkbox is checked or unchecked. The refreshPage() function checks the current state of the checkbox and then reloads the page using location.reload().
This should give you the desired behavior of refreshing the page each time the checkbox is checked or unchecked while keeping the latest value of the checkbox.
Rate this post
5 of 5 based on 1919 votesComments