skip to Main Content

I want the position of the checkbox to be saved when my form is submitted.

The problem with my code is that if the user enables or disables the checkbox; after submitting the form, the checkbox is marked and the user’s choice is not taken into account.

My code:

<?php
function tets_checkBox() {
  if (isset($_POST['submit-post'])) {
    if (isset($_POST['email-post'])) {
      echo '<p class="alert alert-success">' . __('The checkbox is checked.') . '</p>';
    } else {
      echo '<p class="alert alert-danger">' . __('The checkbox is not checked.') . '</p>';
    }
    echo '<p class="alert alert-success">' . __('The settings for your account have been updated') . '</p>';        
  }
}
?>
  
<form method="post" action=" ">             
  <aside class="account_news">
    <label class="account_mainBtn">
      <input type="checkbox" name="email-post" checked>
    </label>
    <h3>Select.</h3>
  </aside>          
  <input type="submit" name="submit-post" value="<?php _e('Update settings'); ?>">          
</form>

2

Answers


  1. you can simply handle by checking isset or empty function when a user check the checkbox you will get the email-post field in action else the field will undefined

    if(!empty($_POST['email-post'])){
     echo '<p class="alert alert-success">' . __( 'The checkbox is checked.' ) . '</p>';
    }else{
     echo '<p class="alert alert-danger">' . __( 'The checkbox is not checked.' ) . '</p>';
    }
    

    the !empty function check both is the variable exists and the variable is not empty. Hope it will help.

    Login or Signup to reply.
  2. $checked_attr = ( isset($_POST['email-post']) ) ? "checked='checked'" : '';
    
    tets_checkBox();
    ?>
    <form method="POST" action="" >
                        
                <aside class="account_news">
    
                     <label class="account_mainBtn">
                         <input type="checkbox" name="email-post" <?php echo $checked_attr; ?>  >
                      </label>
    
                     <h3>Select.</h3>
                </aside>
                            
        <input type="submit" name="submit-post" value="<?php echo( 'Update settings' ); ?>">
                            
    </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search