4

I'm trying to keep a checkbox checked, but after I refresh the page, if the checkbox is checked the database will get updated with 'yes', but the database automatic updates it to 'no' even if the checkbox is checked with local.store, I hope somebody can help me. This is my code.

    <form action="" method="POST">
     <label for="option1">Waarschuwingsbericht inschakelen voordat het volgende pack wordt geopend als jou pack boven de 200.000 waard is?</label><input id='option1' type="checkbox" name="checkbox" value="yes"><br>
      <input type="submit" value="Opslaan en nog een pack openen">
    </form>
<?
    if(isset($_POST['checkbox'])){
        $sql = "UPDATE users SET puntenchecked = 'yes' WHERE username = '" . $usernamez . "'";
        $result = mysql_query($sql) or die('Query failed: ' . mysql_error());
    }
    else {
        $sql = "UPDATE users SET puntenchecked = 'no' WHERE username = '" . $usernamez . "'";
        $result = mysql_query($sql) or die('Query failed: ' . mysql_error());
    }
?>
<script>
$(function(){
    var test = localStorage.input === 'true'? true: false;
    $('input').prop('checked', test || false);
});

$('input').on('change', function() {
    localStorage.input = $(this).is(':checked');
    console.log($(this).is(':checked'));
});
</script>
2
  • You dont need this $('input').prop('checked', test || false);. This should be enough $('input').prop('checked', test); Commented Jan 30, 2016 at 10:04
  • Use checked attribute into <input type="checkbox"> based on $_POST['checkbox'] request is set. See here stack answer already did. Commented Jan 30, 2016 at 10:06

2 Answers 2

2

try this :

<input id='option1' type="checkbox" name="checkbox" value="yes" <?php echo (isset($_POST['checkbox']))? "checked='checked'": "";?> >
Sign up to request clarification or add additional context in comments.

Comments

1

Replace below JS logic:

<script>
$(function(){
    var test = localStorage.input === 'true'? true: false;
    $('input').prop('checked', test);
});

$('input').on('change', function() {
    localStorage.input = $(this).is(':checked');
    console.log($(this).is(':checked'));
});
</script>

Check for more here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.