2011-11-09 54 views
0

我試圖使用JavaScript創建一個文本框的水印,但與當前的代碼中,我得到一個錯誤添加JavaScript文字水印不工作

網頁錯誤的詳細信息 消息:「searchInput」是不確定的

<script type="text/javascript" language="javascript"> 

function watermark(inputId,text){ 

    var inputBox = document.getElementById(searchInput); 

     if (inputBox.value.length > 0){ 

      if (inputBox.value == text) 

        inputBox.value = ''; 
    } 
    else 
     inputBox.value = text; 
} 
</script> 

<input name="keyword2" id="searchInput" type="text" class="searchbox2" 
     value="Enter a State, County, City or Zip" size="77" maxlength="30" 
     onfocus="watermark('searchInput','Enter a State, County, City or Zip');" 
     onblur="watermark('searchInput','Enter a State, County, City or Zip');"/> 
+0

會如此好看,如果所有瀏覽器都支持html5佔位符屬性 – Muleskinner

回答

0

在searchInput周圍添加引號。

getElementById接受一個字符串,你引用一個未聲明的變量。

document.getElementById('searchInput'); 
+0

謝謝,我忘了!你知道如何將輸入中的文本設置爲灰色嗎? – user959443

+0

當然,只需在你的css中添加'#searchInput {color:#666}' – ChrisR

1

變量的函數需要被命名爲inputIdsearchInput ..

所以這條線

var inputBox = document.getElementById(searchInput); 

改變

var inputBox = document.getElementById(inputId); 

一種替代

並避免命名元件完全,只要傳遞this作爲第一個參數,因爲它會引用的元素

function watermark(element, text) { 
    if (element.value.length > 0) { 
     if (element.value == text) { 
      element.value = ''; 
     } 
    } 
    else element.value = text; 
} 

<input name="keyword2" id="searchInput" type="text" class="searchbox2" 
     value="Enter a State, County, City or Zip" size="77" maxlength="30" 
     onfocus="watermark(this,'Enter a State, County, City or Zip');" 
     onblur="watermark(this,'Enter a State, County, City or Zip');"/> 

演示在http://jsfiddle.net/ZtutT/

0

您需要在您的搜索輸入getElementById聲明周圍加上引號,如下所示:

document.getElementById('searchInput');

而且,這樣做的更直接,更簡單的方法是把這個在你輸入:

onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"

希望這有助於:)