2014-04-11 72 views
0

在我的HTML表單中的所有數據成功,除了複選框值驗證複選框值。它不驗證與jquery/ajax請求。無法驗證與jQuery/AJAX

這裏是我的html表單AJAX和HTML代碼(僅條款部分):

<tr> 
<td>Terms & Conditions</td> 
<td><input type="checkbox" name="terms"/>&nbsp; I agree to your <a href="">terms and 
conditions</a>.</td> 

<script> 
    $('#form1').submit(function(event) { 
    event.preventDefault(); 
    $.ajax({ 
    type: 'POST', 
    url: 'regProcess.php', 
    data: $(this).serialize(), 
    dataType: 'json', 
    success: function (data) { 
     $('#info1').html(''); 
     $.each(data, function(key, value) { 

      $('#info1').append('<p>'+value+'</p>'); 
     });  

    } 
    }); 
}); 
</script> 

在regProcess.php頁以下是我的複選框驗證代碼,但它不是驗證..

if(isset($_POST['terms']) && $_POST['terms'] == ""){ 
    $msg[] = "You must agree our terms and conditions"; 
    $msg1['error'] = true; 
    } 
+0

看到這個http://stackoverflow.com/questions/11424037/does-input-type-checkbox-only-post-data-if-its-checked – KrIsHnA

+0

在這裏你可以得到一個回答:http://stackoverflow.com/questions/19893927/send-checkbox-value-in-php-form – KrIsHnA

回答

0

如果它是未選中的複選框,則不會設置。它應該改爲:

if (empty($_POST['terms']) || $_POST['terms'] !== 'on') { 

或只是

if (empty($_POST['terms'])) { 
+0

我不明白。 – Babu

+0

你的PHP腳本沒有返回錯誤的原因是因爲你正在檢查'$ _POST ['terms']'是否被設置,它不是。看到我更新的答案。 –

+0

哦,很好,你的答案是工作。但我不明白你爲什麼使用'on'? – Babu

0

給複選框ID

<tr> 
<td>Terms & Conditions</td> 
<td><input type="checkbox" id="terms" name="terms"/>&nbsp; I agree to your <a href="">terms and 
conditions</a>.</td> 

然後用它來找出複選框被選中或不?

<script> 
    $('#form1').submit(function(event) { 
    event.preventDefault(); 
    if($('#terms').is(':checked')) 
    { 

    $.ajax({ 
    type: 'POST', 
    url: 'regProcess.php', 
    data: $(this).serialize(), 
    dataType: 'json', 
    success: function (data) { 
     $('#info1').html(''); 
     $.each(data, function(key, value) { 

      $('#info1').append('<p>'+value+'</p>'); 
     });  

    } 
    }); 
    } 
else{ 
alert("Check terms and condition"); 
} 
}); 
</script> 

Live Example

+0

我應該把你的代碼?在regProcess.php或html頁面? – Babu

+0

它的jquery,所以一定是客戶端在這裏! :) – KrIsHnA

+0

我認爲他建議你不要使用ajax,只要確保使用javascript檢查了該框。 –