jquery在更改时提交复选框


jquery to submit on change checkbox

我有以下代码,但问题是,如果我使用普通的提交按钮,一切都很好,但如果我想用jquery onchange提交复选框值,它就不起作用(即数据库中没有任何内容)。。。我甚至尝试过在构造中附加onChange=this.form.submit()的非jquery路由。有人知道发生了什么/怎么解决这个问题吗?在我看来,表单是在未处理数据的情况下提交的。

我还使用:https://github.com/ghinda/css-toggle-switch对于复选框

JQUERY:

$('#construction').change(function() {
  this.form.submit();
});

PHP:

<?php
$config = mysql_query("SELECT construction FROM config") or die(mysql_error());
$row_config = mysql_fetch_assoc($config);
if ($_POST) {
    // 0 = off
    // 1 = on
    $constr = $_POST['construction'];
    if ($constr == 'on') { $c = 0; } else { $c = 1; }
    mysql_query("UPDATE config SET construction = '".$c."'") or die(mysql_error());
    redirect('index.php');
}
?>

HTML:

<div style="margin-top:30px;">
        <form action="index.php" method="post" id="doSite">
            <fieldset class="toggle">
                <input id="construction" name="construction" type="checkbox"<?php if($row_config['construction'] == '0') { echo ' checked'; } ?>>
                <label for="construction">Site construction:</label>
                <span class="toggle-button"></span>
            </fieldset>
            <input name="Submit" type="submit" value="Shutdown site" class="button">
        </form>
    </div>

试试这个,

$('#construction').change(function() {
  $(this).closest("form").submit();
});

演示

将jquery更改为:

$('#construction').change(function() {
  $("#doSite").submit();
});

doSite是您的表单id,因此当复选框被选中或取消选中时,您可以直接使用它来提交表单。

我更新了您的代码:
-使用isset检查是否设置了变量-表单提交时未选中的复选框不包括在$_POST数据中:这意味着您只需检查是否设置了$_POST["构造"](其值无关紧要)
-由于您在mysqlquery中使用双引号,因此不需要连接。而且,如果construction字段是INT类型,您可以删除$c 周围的单引号

<?php
$config = mysql_query("SELECT construction FROM config") or die(mysql_error());
$row_config = mysql_fetch_assoc($config);
if(isset(($_POST))
{
    // 0 = off
    // 1 = on
    if(isset($_POST['construction']))
        $c = 1;
    else
        $c = 0;
    mysql_query("UPDATE config SET construction = '$c'") or die(mysql_error());
    redirect('index.php');
}
?>

注意:所有的mysql_*函数总有一天会被弃用和删除。如果可能的话,您应该使用MySQLi或PDO
更多信息:
http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
http://php.net/manual/en/mysqlinfo.api.choosing.php

为什么不使用:

$("#checkid").click(function(){

})