use*_*849 31 javascript php forms checkbox search
有没有办法在选中复选框时提交表单?
<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';
}
?>
Run Code Online (Sandbox Code Playgroud)
这就是我目前所拥有的,但是当用户选中或取消选中复选框时,我想在没有提交按钮的情况下提交表单.有帮助吗?
Sli*_*liq 68
在简单的JavaScript中简单地说
onChange="this.form.submit()"
Run Code Online (Sandbox Code Playgroud)
进入表单/输入标记.
Sur*_*ams 15
是的,这是可能的.
<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>
Run Code Online (Sandbox Code Playgroud)
通过添加onchange="document.getElementById('formName').submit()"到每个复选框,您可以在任何时候更改复选框.
如果你对jQuery没问题,那就更容易了(而且不引人注目):
$(document).ready(function(){
$("#formname").on("change", "input:checkbox", function(){
$("#formname").submit();
});
});
Run Code Online (Sandbox Code Playgroud)
对于表单中的任意数量的复选框,当"更改"事件发生时,表单将被提交.如果您通过该.on()方法动态创建更多复选框,这甚至可以工作.
小智 9
我已经搞砸了大约四个小时,并决定与您分享。
您可以通过单击复选框来提交表单,但奇怪的是,在 php 中检查提交时,您会期望在选中或取消选中复选框时设置表单。但是这是错误的。仅当您实际选中该复选框时,该表单才会被设置,如果取消选中它,则不会被设置。复选框输入类型末尾的“checked”一词将导致复选框显示为“checked”,因此,如果您的字段被选中,则必须反映出来,如下例所示。当它被取消选中时,php 会更新字段状态,这将导致单词“checked”消失。
您的 HTML 应该如下所示:
<form method='post' action='#'>
<input type='checkbox' name='checkbox' onChange='submit();'
<?php if($page->checkbox_state == 1) { echo 'checked' }; ?>>
</form>
Run Code Online (Sandbox Code Playgroud)
和 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;
}
}
Run Code Online (Sandbox Code Playgroud)
$(document).ready(
function()
{
$("input:checkbox").change(
function()
{
if( $(this).is(":checked") )
{
$("#formName").submit();
}
}
)
}
);
Run Code Online (Sandbox Code Playgroud)
虽然最好将类添加到每个复选框并执行
$(".checkbox_class").change();
Run Code Online (Sandbox Code Playgroud)
这样您就可以选择哪些复选框提交表单,而不是所有复选框都提交表单。