Daniel Daniel - 7 months ago 27
Javascript Question

How to fill in data in an input field using javascript directly on page load?

This question has been a lot over stackoverflow but none of the solution seems to be working. I am developing a web application where I have to fill in data in data fields in page load. Here is my code:

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<input type="text" id="datetime" value="" />
<script type="text/javascript">
$(document).on("pageload",function(){
//for fill field
document.getElementById("datetime").value = "here is value";
});
</script>


</body>
</html>


For some reason, when i load the page, no data gets filled in, does anyone see the reason for it?

Answer

You don't need jQuery. Try this:

<!DOCTYPE html>
<html>

<body>
  <input type="text" id="datetime" value="" />

  <script>
    window.onload = function() {
      document.getElementById('datetime').value = 'here is value';
    };
  </script>

</body>

</html>