如何在页面加载时获取文本框的值,如果它为null

How to get value of textbox on page load, if it is null?

本文关键字:如果 null 取文本 加载 获取      更新时间:2023-09-26
  1. 首先要检查的是,文本框在页面加载时不包含任何内容吗
  2. 然后给它赋值。

    if (document.getElementById("txtBoxID").value == null) {
    document.getElementById("txtBoxID").value = "Some text here";
    }
    
  3. 但是出错了"JavaScript运行时错误:无法设置未定义或null引用的属性'value'"如何做到这一点?

这是因为您的DOM还没有准备好,所以请等待加载完成:

window.onload=function(){
  if (document.getElementById("txtBoxID").value == null) {
    document.getElementById("txtBoxID").value = "Some text here";
  }
};

您可能试图在页面中定义之前访问元素,所以您应该在window.load事件上执行该代码,或者将该代码移动到</body> 之前

作为替代方案,您可以使用许多现代浏览器支持的placeholder属性

<input type="text" id="txtBoxId" placeholder="Some text here" />

如果输入没有值,则会显示占位符值
(这种行为的polyfill可用于旧浏览器)

您试图访问null(或未定义)对象的属性'value',这会导致异常,假设您的ID可能不是txtBoxID

测试文本框值为null是不安全的。您应该使用空字符串。我创建了一个jsFiddle,显示如下:

<input type="text" id="txtBx" />
document.getElementById("txtBx").value = null;
alert("test 1 textbox is null 'n" +  (document.getElementById("txtBx").value == null));
alert("test 2 textbox is empty string 'n" +  (document.getElementById("txtBx").value == ""));

http://jsfiddle.net/kZhHa/3/

(我使用的是Chrome)

页面加载后,您是否正在执行上面的代码?

window.onload = function() {
  if (document.getElementById("txtBoxID").value == null) {
    document.getElementById("txtBoxID").value = "Some text here";
  }
}

注意,window.onload并不是检查页面是否已加载的最佳方式。这取决于浏览器的规格。请参阅window.addEventListener或window.attachEvent或IE.

请尝试下面的代码,您需要在行中首先将值设置为null

Name: <input type="text" id="myText" value=''>

这是演示:

function func() {
  if (document.getElementById("myText").value == '') {
    document.getElementById("myText").value = "Some text here";
  } else {
    alert("not null");
  }
}
Name: <input type="text" id="myText" value="">
<p>Click the button to change the value of the text field.</p>
<input type="button" id="button" value="Click Me" onClick="func();" />

如果您有JQuery,这里还有另一种实现您所要求的方法。在document.ready函数中,您可以使用文本框的id获取文本的值,并将其包装在JQuery中。这将允许您使用.val()函数在文本框为空的情况下检查并替换文本框的值

$(document).ready(function () {         
    if($('#id-of-your-textbox').val() == ' ') 
    {
       $('#id-of-your-textbox').val('some text');
    }
});