简体   繁体   中英

Submit form when a checkbox is checked and getting data with POST

this is my form :

 <form class="form-horizontal" method="post" action=""  id="user_profile_private" name="user_profile_private">         
 <div class="onoffswitch">      
     <input type="checkbox" name="onoffswitch"  class="onoffswitch-checkbox" id="myonoffswitch" checked>
     <label class="onoffswitch-label" for="myonoffswitch">
     <div class="onoffswitch-inner"></div>
     <div class="onoffswitch-switch"></div>
    </label>
 </div>

I've tried onChange="this.form.submit()" and Onchange="document.getElementById('formName').submit()" . In some point, I even succeed to submit my form but I could not be successful on getting the data. What I want is to submit the form and get the data (if the checkbox (swich) on or off) in the same page with $_POST.

PS: I made this switch with http://proto.io/freebies/onoff/ maybe it helps.

The important thing is getting data with post because when I try to do that I always get an empty array with var_dump($_POST);

You can use jquery $('selector').on('click'); or $.click() on this one. Consider this example:

<?php
// PHP form handling:

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $checkbox_value = $_POST['onoffswitch'];
    echo '<script>alert("'.$checkbox_value.'");</script>';
}
?>

<!-- change the action="" to the name of this php file -->
<form class="form-horizontal" method="POST" action="index.php"  id="user_profile_private" name="user_profile_private">           
    <div class="onoffswitch">      
        <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" value="1">
        <label class="onoffswitch-label" for="myonoffswitch">
            <div class="onoffswitch-inner"></div>
            <div class="onoffswitch-switch"></div>
        </label>
    </div>
</form>

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    $('#myonoffswitch').on('click', function(){
        if($(this).is(':checked')) {
            // if your checkbox is checked, submit the form
            $('#user_profile_private').submit();
        }
    });

});
</script>

Do something like that

$('.myonoffswitch').on('click',function(){

  if($(".myonoffswitch").is(':checked'))
     DO SOMETHING....
  else
      DO SOMETHING....
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM