2013-03-17 94 views
0

如何在用户再次纠正输入后隐藏/删除分配给每个字段的错误消息?当输入无效时,下面的脚本将显示错误消息,但是当用户再次键入有效值并单击按钮时,错误消息仍然存在,如何解决?jQuery在重新验证正确的输入时隐藏/删除错误消息

这是回调

$('#btn_register').click(function(){ 
    var parameters = $('#register_form').serialize(); 
    $.ajax({ 
     url: 'request.php', 
     type: 'POST', 
     data: parameters, 
     dataType: 'json', 
     success: function(response){ 
      if(response.success == 'success'){ 

       alert('Success'); 
       $('#register_form')[0].reset(); 

      }else{ 
       if(response.error.email != ''){ 
        $('#email_error').html(response.error.email); 
       } 
       if(response.error.password != ''){ 
        $('#password_error').html(response.error.password); 
       } 
       if(response.error.rpassword != ''){ 
        $('#rpassword_error').html(response.error.rpassword); 
       } 
       if(response.error.fname != ''){ 
        $('#fname_error').html(response.error.fname); 
       } 
       if(response.error.contact != ''){ 
        $('#contact_error').html(response.error.contact); 
       } 
       if(response.error.dob != ''){ 
        $('#dob_error').html(response.error.dob); 
       } 
       if(response.error.captcha != ''){ 
        $('#captcha_error').html(response.error.captcha); 
       } 
      } 
     }, 
     error: function(){ 
      console.log(arguments); 
     } 
    }); 

}); 

这是表单字段中显示错误消息时回调无效:

<input type="text" id="email" name="email" /><br /><span class="error" id="email_error"></span> 

请告知和感谢。

回答

0

在给定的标记,我会做这样

success: function(response){ 
    if(response.success == 'success'){ 
     ..... 
    } else { 
     $('[id$="_error"]').html(''); 

     $.each(response.error, function(key, value){ 
      if(value){ 
       $('#' + key + '_error').html(value); 
      } 
     }); 
    } 
} 

东西要清除所有的错误信息,逻辑是基于所有的错误占位符元素有id属性与_error结束的假设,然后用attribute ending with selector

$('[id$="_error"]').html(''); 

但我会建议增加一类像error-label到所有的错误占位,改变$('[id$="_error"]').html('')$('.error-label').html('')

+0

谢谢!工作真棒。 – conmen 2013-03-17 12:22:28

0

试试这个:

<input type="text" id="email" name="email" onChange="resetInput(this);"/> 

function resetInput(placeholder) { 
     $('#'+$('placeholder').attr('id')+'_error').text(''); 
} 

或尝试在阿贾克斯成功:

success :function() { 
    $('[id$="_error"])').text(''); 
if(response.success == 'success'){ 
       alert('Success'); 
       $('#register_form')[0].reset(); 
      }else{...............} 
    }