简体   繁体   中英

How to populate an HTML field using javascript?

I have this script to pick a date in a form:

<script src="http://trentrichardson.com/examples/timepicker/js/jquery-ui-timepicker-addon.js"></script>
  <script>
  $(document).ready(function() {
     $('#datetime1').datetimepicker();
  });
  </script>

and here is the form:

<form action="#" method="get">
<input type="text" name="date1" id="datetime1" value = "03/14/2012 00:00"/> 
</form>

How can I combine the following script with the datepicker script so that the form is automatically populated with today's date which can then be changed?

<!--this prints current date-->
<script type="text/javascript">
<!--
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
-->
</script>
$(function(){
     var currentTime = new Date()
     var month = currentTime.getMonth() + 1
     var day = currentTime.getDate()
     var year = currentTime.getFullYear()
     $('#datetime1').val(month + "/" + day + "/" + year).datetimepicker();
});

Do this (jQuery) :

$('#datetime1').val(month + "/" + day + "/" + year);

or (JavaScript) :

document.getElementById('datetime1').value = month + "/" + day + "/" + year;

instead of

document.write(month + "/" + day + "/" + year)

The second (jQuery) options uses the .val() method to set a value of a DOM element with the id ( # ) of datetime1 . And may i suggest this mozilla JavaScript tutorial as a great place to start learning

If I understood your question, you are trying to pre-populate your input with the current day:

javascript:

document.getElementById('datetime1').innerHTML = month + "/" + day + "/" + year;

jquery:

$('#datetime1').val(month + "/" + day + "/" + year);

Use the document ready function for when the page loads and set the value then

$(document).ready(function () {
  $('#datetime1').val(month + "/" + day + "/" + year);
});

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM