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

时间:2014-05-16 05:26:31

标签: javascript php html

这是我的表格:

 <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在同一页面中获取数据(如果打开或关闭复选框(swich))。

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

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

2 个答案:

答案 0 :(得分:3)

您可以在此处使用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>

答案 1 :(得分:1)

做那样的事

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

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