2012-05-15 53 views
20

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

<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'; 
    } 
?> 

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

回答

40

在普通的JavaScript简单地把

onChange="this.form.submit()" 

到表单/输入标签。

+0

哇,这么简单! –

+0

如何添加javascript确认? –

12

是的,这是可能的。

<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()方法。

+0

我已经实现了这个代码,但是当我检查复选框时,搜索结果不显示。我需要改变php代码吗? – user1394849

+0

它与PHP无关 - 请检查您的JavaScript控制台以确保没有错误。如果您点击提交,它会起作用吗? –

+0

完全没有错误,我已经尝试了您给我的两条建议。 – user1394849

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

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

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

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

0

我一直在为此乱搞四个小时左右,并决定与你分享。

你可以通过点击一个复选框来提交表单,但奇怪的是,当检查提交在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; 
     } 
} 
相关问题