2013-03-17 50 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{...............} 
    }