2015-02-06 89 views
2

嘿,我有一個登錄表單,當您點擊輸入時,標籤向上移動,焦點移出後,它會檢查輸入中是否有文本,以及如果標籤保持不變不要把標籤掉下來。JQuery檢查輸入是否爲頁面加載時爲空

我的代碼是:

$(function() { 
    $('.loginForm .inputGroup input').focusout(function() { 
     var text_val = $(this).val(); 
     if (text_val === "") { 
      $(this).removeClass('has-value'); 
     } else { 
      $(this).addClass('has-value'); 
     } 
    }); 
}); 

問題是,當我點擊登錄,它給像用戶名的錯誤不存在我想保持對輸入的用戶名,但是當我做了標籤住宿在輸入文本的頂部。
如何在輸入時檢查負載是否有文本?

圖像,以幫助瞭解情況:

enter image description here enter image description here

的jsfiddle: http://jsfiddle.net/16g7yhLf/

乾杯!

回答

6

您可以在註冊事件處理程序後觸發focusout事件,以便處理程序得到執行。

$(function() { 
    $('.loginForm .inputGroup input').focusout(function() { 
     var text_val = $(this).val(); 
     if (text_val === "") { 
      $(this).removeClass('has-value'); 
     } else { 
      $(this).addClass('has-value'); 
     } 
    }).focusout();//trigger the focusout event manually 
}); 

演示:Fiddle


一個較短的版本可以

$(function() { 
    $('.loginForm .inputGroup input').focusout(function() { 
     var text_val = $(this).val(); 
     $(this).toggleClass('has-value', text_val !== ""); 
    }).focusout(); //trigger the focusout event manually 
}); 
+0

謝謝你,它的工作:) – Matthew 2015-02-06 14:00:35