Foxy
Foxy

Reputation: 416

How to use onload inside form input?

I have a function:

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;


}

And html form input:

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

Why I am not getting default date when page loads?

Upvotes: 1

Views: 7691

Answers (2)

IrkenInvader
IrkenInvader

Reputation: 4050

Your input has name="startDate", but you are trying to look it up by Id.

Set the proper Id on your input.

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

I also manually called loadDefaultDate in javascript. As adeneo's comment mentions, onload does not work with input elements.

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();

Upvotes: 1

Jorge Mejia
Jorge Mejia

Reputation: 1163

Try with this:

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

Upvotes: 1

Related Questions