2012-07-30 93 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(){ 

})