当复选框被选中并使用POST获取数据时提交表单

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

本文关键字:获取 POST 数据 表单 提交 复选框      更新时间:2023-09-26

这是我的表单:

 <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>

我试过onChange="this.form.submit()"Onchange="document.getElementById('formName').submit()"。在某些情况下,我甚至成功提交了表单,但我无法成功获取数据。我想要的是提交表单,并获得数据(如果复选框(开关)打开或关闭)在同一页面与$_POST。

PS:我用http://proto.io/freebies/onoff/做了这个开关,也许它有帮助。

重要的是通过post获取数据因为当我尝试这样做时我总是得到一个空数组var_dump($_POST);

您可以使用jquery $('selector').on('click');$.click()在这个。考虑这个例子:

<?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>

做点类似的事情

$('.myonoffswitch').on('click',function(){
  if($(".myonoffswitch").is(':checked'))
     DO SOMETHING....
  else
      DO SOMETHING....
});