![](/img/trans.png)
[英]document.getElementById().value returning empty string instead of value of textfield
[英]Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box
我有一個文本框元素,我試圖使用document.getElementById("id-name").value
訪問其document.getElementById("id-name").value
。 我發現調用返回的是 null 而不是空字符串。 返回值的數據類型仍然是字符串。 null 是字符串值嗎?
<input type="text" value="" id="mytext">
是我試圖使用var mytextvalue = document.getElementById("mytext").value;
獲取其值的文本框var mytextvalue = document.getElementById("mytext").value;
發布您的 HTML 可能會有所幫助。 相反,您可以先獲取元素,然后檢查它是否為空,然后詢問其值,而不是直接詢問該值而不知道該元素是否在 HTML 上可見。
element1 = document.getElementById(id);
if(element1 != null)
{
//code to set the value variable.
}
僅供參考,如果您在輸入標簽上使用 html type="number" 屬性,就會發生這種情況。 在您的腳本知道發生了什么之前,輸入一個非數字將清除它。
對於您的代碼
var mytextvalue = document.getElementById("mytext");
如果在此代碼之前有document.write()
語句,則mytextvalue
將包含null
。 所以刪除document.write
語句,你應該在變量mytextvalue
得到一個正確的文本對象。
這是由document.write
更改文檔引起的。
try this...
<script type="text/javascript">
function test(){
var av=document.getElementById("mytext").value;
alert(av);
}
</script>
<input type="text" value="" id="mytext">
<input type="button" onclick="test()" value="go" />
請檢查這個小提琴,如果您收到空值警報,請告訴我。 我已經在那里復制了您的代碼並添加了一些警報。 就像其他人一樣,我也沒有看到返回空值,我得到一個空字符串。 您使用的是哪個瀏覽器?
這個演示在 Chrome 14、FF3 和 FF5(使用 Firebug)中為我正確返回:
var mytextvalue = document.getElementById("mytext").value;
console.log(mytextvalue == ''); // true
console.log(mytextvalue == null); // false
並將console.log
更改為alert
,我仍然在 IE6 中獲得所需的輸出。
我認為在執行 javascript 時,您嘗試訪問的文本框尚未加載到頁面上。
即,為了讓 Javascript 能夠從頁面的 DOM 讀取文本框,文本框必須作為元素可用。 如果在將文本框寫入頁面之前調用 javascript,則文本框將不可見,因此返回 NULL。
您似乎在 HTML 標記中省略了 value 屬性。
將其添加為<input value="" ... >
。
如果您使用外部 js 文件,請在關閉</html>
標記之前在末尾添加<script src="fileName.js"></script>
。 或者在關閉 html 標簽之前將<script>
放在最后。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.