![](/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.