2010-10-11 118 views
1

我正在使用jquery進行字段驗證以檢查它是否爲空。如果是我想顯示一條消息,然後重新調整該字段,以便用戶可以輸入一些數據。代碼:JQuery驗證問題


$('#fieldId').blur(function() { 
    var fieldValue = $(this).val(); 
    if(fieldValue == null || fieldValue.length == 0) { 
     $(this).addClass('error'); 
     // show error message 
     $('#errorDivId') 
      .text('You must enter a value in this field') 
      .show(); 
     $(this).focus(); 
    } 
    else { 
     if ($(this).is('.error')) { 
      $(this.removeClass('error'); 
      $('#errorDivId').hide() 
     } 
    } 
}); 

它的工作類型,但它將光標移動到下一個領域,而不是我重新聚焦。

回答

3

你可以試試這個:

$('#fieldId').blur(function(evt) { 
    var fieldValue = $(this).val(); 
    if(fieldValue == null || fieldValue.length == 0) { 
    $(this).addClass('error'); 
    // show error message 
    $('#errorDivId') 
     .text('You must enter a value in this field') 
     .show(); 
    this.focus(); 
    evt.preventDefault(); 
    } 
    else { 
    if ($(this).is('.error')) { 
     $(this.removeClass('error'); 
     $('#errorDivId').hide() 
    } 
    } 
}); 

但是可能不能完全解決問題,因爲有些瀏覽器可能會混淆。作爲替代,包住「焦點」調爲超時和當前事件結束後運行它:

var self = this; 
    setTimeout(function() { self.focus(); }, 1); 

這是一個黑客樣,但它也應該工作。

編輯 — @Gus是正確的哪些 「重點()」 來稱呼

+0

偉大工程 - 感謝 – RWBear 2010-10-11 17:43:13

2

blur事件在焦點更改期間觸發(因爲您正在驗證的控件失去焦點)。這可能會導致奇怪的行爲,如果你試圖改變焦點,而它已經在改變。請嘗試將驗證附加到change事件中,而不是blur

此外,沒有必要調用jQuery版本的焦點:$(this).focus(),您可以撥打this.focus()

$('#fieldId').change(function() { 
    var fieldValue = $(this).val(); 
    if(fieldValue == null || fieldValue.length == 0) { 
     $(this).addClass('error'); 
     // show error message 
     $('#errorDivId').text('You must enter a value in this field').show(); 
     this.focus(); 
    } else { 
     if ($(this).is('.error')) { 
      $(this).removeClass('error'); 
      $('#errorDivId').hide() 
     } 
    } 
});