【问题标题】:Can't validate checkbox value with jquery /ajax无法使用 jquery /ajax 验证复选框值
【发布时间】:2014-05-25 23:31:05
【问题描述】:

在我的 html 表单中,除复选框值外,所有数据均已成功验证。它不适用于 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 页面下面是我的 Checkbox 验证代码,但它没有验证..

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

【问题讨论】:

标签: php jquery ajax


【解决方案1】:

给复选框一个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>

然后用这个来判断checkbox是否被选中??

<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

【讨论】:

  • 我应该把你的代码放在哪里?在 regProcess.php 或 html 页面中?
  • 它的jquery,所以这里必须是客户端! :)
  • 我认为他是在建议您不要使用 ajax,只需确保使用 javascript 选中该框即可。
  • 我有单独的 php 页面,它处理所有错误并显示所有错误 echo json_encode($msg); 到 html 页面。那么现在我该怎么办?
  • 它的客户端验证。使用jQuery。你也可以使用服务器端
【解决方案2】:

$_POST['terms'] 如果是未选中的复选框,则不会设置。它应该是:

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

或者只是

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

【讨论】:

  • 您的 php 脚本没有返回错误的原因是因为您正在检查是否设置了 $_POST['terms'],但实际上没有。请参阅我的更新答案。
  • 哦,太好了,你的回答很有效。但我不明白你为什么使用on
  • 您可能会忽略它而只使用if (empty($_POST['terms'])) {,但如果您不指定自己的值,网络浏览器会将字符串“on”作为选中复选框的值发送。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多