提交表单时,一个复选框被选中(submitting a form when a checkbox i

2019-06-24 11:22发布

是有办法提交表单时复选框被选中?

<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
    <input type ="checkbox" name="cBox[]" value = "3">3</input>
    <input type ="checkbox" name="cBox[]" value = "4">4</input>
    <input type ="checkbox" name="cBox[]" value = "5">5</input>
    <input type="submit" name="submit" value="Search" />
</form>

<?php
    if(isset($_GET['submit'])){
        include 'displayResults.php';
    }
?>

这是我目前的,但我想提交表单没有提交按钮,当用户选中或取消选中的复选框。 任何帮助吗?

Answer 1:

在普通的JavaScript简单地说

onChange="this.form.submit()"

到表单/输入标签。



Answer 2:

是的,这是可能的。

<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
    <input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input>
    <input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input>
    <input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input>
    <input type="submit" name="submit" value="Search" />
</form>

通过添加onchange="document.getElementById('formName').submit()"到每个复选框,你会提交复选框被更改的任何时间。

如果你使用jQuery OK,那就更简单了(和不显眼):

$(document).ready(function(){
    $("#formname").on("change", "input:checkbox", function(){
        $("#formname").submit();
    });
});

对于任何数量的表单复选框,当“变”事件发生时,提交表单。 如果动态地创建更感谢复选框这会甚至工作.on()方法。



Answer 3:

$(document).ready(
    function()
    {
        $("input:checkbox").change(
            function()
            {
                if( $(this).is(":checked") )
                {
                    $("#formName").submit();
                }
            }
        )
    }
);

虽然它可能会是更好的类添加到每个复选框并做

$(".checkbox_class").change();

这样您就可以选择复选框提交表单,而不是所有的人都这样做。



Answer 4:

我一直在瞎搞这个约四小时,并决定与大家分享。

您可以通过点击复选框提交表单,但奇怪的是,在PHP提交检查的时候,你会期望形式来设定,当您选中或取消选中该复选框。 但是,这是不正确的 。 该表格只有被设定,当你真正选中该复选框,如果你取消它也不会被设置。 在一个复选框输入类型的端检查该字将导致复选框以显示选中,因此,如果您字段被选中,将具有以反映像在下面的例子。 当它得到未选中状态PHP更新场状态,这将导致字检查消失。

你的HTML应该是这样的:

<form method='post' action='#'>
<input type='checkbox' name='checkbox' onChange='submit();'
<?php if($page->checkbox_state == 1) { echo 'checked' }; ?>>
</form>

和PHP:

if(isset($_POST['checkbox'])) {
   // the checkbox has just been checked 
   // save the new state of the checkbox somewhere
   $page->checkbox_state == 1;
} else {
   // the checkbox has just been unchecked
   // if you have another form ont the page which uses than you should
   // make sure that is not the one thats causing the page to handle in input
   // otherwise the submission of the other form will uncheck your checkbox
   // so this this line is optional:
      if(!isset($_POST['submit'])) {
          $page->checkbox_state == 0;
      }
}


文章来源: submitting a form when a checkbox is checked