【问题标题】:jquery to submit on change checkboxjquery 提交更改复选框
【发布时间】:2012-07-30 00:47:21
【问题描述】:

我有以下代码,但问题是,如果我使用普通的提交按钮,一切正常,但如果我想用 jquery onchange 提交复选框值,它就不起作用(即没有任何东西进入数据库)...我什至尝试使用附加到构造的onChange=this.form.submit() 的非jquery 路线。任何人都知道发生了什么/如何解决这个问题?对我来说,表单似乎是在不处理数据的情况下提交的。

我也在使用:https://github.com/ghinda/css-toggle-switch 复选框

查询:

$('#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>

【问题讨论】:

    标签: php jquery checkbox submit


    【解决方案1】:

    试试这个,

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

    DEMO

    【讨论】:

    • 看起来好像是在处理复选框之前提交。知道为什么吗?数据没有进入数据库
    • 你用&lt;?php print_r($_POST) ?&gt;检查过发布的数据吗?
    【解决方案2】:

    将您的 jquery 更改为:

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

    doSite是你的form id,所以你可以在checkbox被选中或者不选中的时候直接使用它来提交form。

    我更新了你的代码:
    - 使用isset 检查是否设置了变量 - 提交表单时未检查的复选框不包含在 $_POST 数据中:这意味着您只需检查是否设置了 $_POST['construction'](其值无关紧要)
    - 由于您在 mysql_query 中使用双引号,因此无需连接。并且,如果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_* 函数都将被弃用和删除。如果可能,您应该改用MySQLiPDO
    更多信息:
    http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
    http://php.net/manual/en/mysqlinfo.api.choosing.php

    【讨论】:

    • 谢谢。我按照您的建议更新了代码,但是我仍然遇到数据没有进入数据库的问题。似乎它在处理复选框之前提交。知道为什么吗?
    【解决方案3】:

    你为什么不使用:

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

    })

    【讨论】:

      猜你喜欢
      • 2014-04-06
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多