如何在表单输入中使用onload?

时间:2016-03-11 21:27:26

标签: javascript html

我有一个功能:

function loadDefaultDate(){

    var currentDate = new Date();
    var curYear, curMonth, curDay;

    curYear = currentDate.getFullYear();
    curMonth = ("0" + (currentDate.getMonth() + 1)).slice(-2);
    curDay = ("0" + currentDate.getDate()).slice(-2);

    document.getElementById("startDate").value = curYear + "-" + curMonth + "-" + curDay;


}

和html表单输入:

<input type=text name="startDate" size=10 maxlength=10 onload="loadDefaultDate()" onclick="javascript:resetValues();">

为什么我在页面加载时没有获取默认日期?

2 个答案:

答案 0 :(得分:1)

您的输入有name="startDate",但您正在尝试按ID查找。

在输入中设置正确的ID。

<input type=text name="startDate" id="startDate" size=10 maxlength=10  onclick="javascript:resetValues();">

我还在javascript中手动调用了loadDefaultDate。正如adeneo的评论所述,onload不适用于input元素。

function loadDefaultDate(){
    var currentDate = new Date();
    var curYear, curMonth, curDay;

    curYear = currentDate.getFullYear();
    curMonth = ("0" + (currentDate.getMonth() + 1)).slice(-2);
    curDay = ("0" + currentDate.getDate()).slice(-2);

    document.getElementById("startDate").value = curYear + "-" + curMonth + "-" + curDay;
}

loadDefaultDate();

答案 1 :(得分:1)

Try with this:

  function load() {
    console.log("load event detected!");
  }
  window.onload = load;