2012-07-30 91 views
0

我有以下代码,但问题是,如果我使用正常提交按钮一切工作正常,但如果我想提交与jQuery的onchange复选框值它不起作用(即没有什么是进入数据库)...我试图甚至去非jQuery的路线与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> 

回答

2

试试这个,

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

DEMO

+0

几乎好像处理复选框前的提交。任何想法为什么?数据不会进入db – Alex 2012-07-30 14:45:14

+0

您是否使用'<?php print_r($ _ POST)?>'检查了发布的数据? – ocanal 2012-07-30 14:52:20

1

您的jQuery更改为:

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

doSite是你的表单ID,所以你可以用它直接提交表单时,该复选框被选中或取消选中。

我更新了你的代码:
- 使用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

+0

谢谢。我按照你的建议更新了代码,但是我仍然遇到了数据不会进入数据库的问题。它几乎看起来好像它在处理复选框之前提交。任何想法为什么? – Alex 2012-07-30 14:44:51

0

为什么不ü使用:

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

})