我需要用计算的日期填充文本框,但无法显示计算的值。 例如文本框应默认为今天的日期 + 5 天。 我有 java 脚本进行计算并且它们正在工作,并且我知道我使用文本框的“value”属性,但不确定将 java 脚本 var 解析为 value 属性的语法。
var currentTime = new Date()
var day = currentTime.getDate() +5
var year = currentTime.getFullYear()
var month = currentTime.getMonth() + 1;
var calcdate = day + "/" + month + "/" + year;
<input type="text" name="T1" size="20" id="sub_date" value="<document.write(subdate)">
最佳答案
我可能会首先获取您的计算日期(和相关变量)并将其粘贴到函数中:
function calculate_date() {
currentTime = new Date();
day = currentTime.getDate() + 5;
year = currentTime.getFullYear();
month = currentTime.getMonth() + 1;
calcdate = day + "/" + month + "/" + year;
return calcdate;
}
我们可以设置另一个小函数,它实际上会将日期插入所需的元素中:
function prepopulate_date() {
document.getElementById("sub_date").setAttribute('value', calculate_date());
}
上面的操作与您之前想要做的相同,但方式稍微简洁一些。
最后,我们需要实际调用这个函数。到目前为止,我们只设置了函数来为我们完成工作,我们实际上还没有告诉它们运行。最重要的是,在尝试向其中插入任何内容之前,我们需要确保该元素确实“存在”。一个常见的问题是,如果您不在加载或“就绪”事件(据我所知,只有在使用外部 javascript 库时才会出现的事件)上执行此操作,您将尝试将值插入到元素尚不存在,因为浏览器还没有时间加载页面的整个 html 内容。所以我们可以做如下事情:
window.onload = prepopulate_date;
如果您愿意,可以下载 example .
我希望这有帮助。干杯。
关于javascript - 使用计算值预填充表单默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1252627/