2010-03-19 65 views
13

如何檢查textarea是否包含任何內容?如何檢查一個Textarea在Javascript或Jquery中是否爲空?

我tryed與此代碼

if(document.getElementById("field").value ==null) 
{ 
    alert("debug"); 
    document.getElementById("field").style.display ="none"; 
} 

但它沒有做什麼,我期待。 我期望它應該出現一個消息框「調試」,並沒有顯示textarea。

我該如何解決這個問題?

回答

21

你想檢查值是否爲== ""而不是NULL

if(document.getElementById("field").value == '') 
{ 
    alert("debug"); 
    document.getElementById("field").style.display ="none"; 
} 

UPDATE

一個working example

而且another one using TRIM如果你想確保他們不會發布空間

執行情況TRIM()

String.prototype.trim = function() { 
    return this.replace(/^\s+|\s+$/g,""); 
} 
+2

您可能也想調整值。 – Alsciende

+0

很酷的想法@Alsciende,加入了它的一個版本 –

+0

謝謝你爲我工作 – streetparade

2

您可以使用下面的jQuery逃避空格爲好。

if($("#YourTextAreaID").val().trim().length < 1) 
{ 
    alert("Please Enter Text..."); 
    return; 
} 
相關問題