In this section you will learn how to display current date in text box using JavaScript.
In this section you will learn how to display current date in text box using JavaScript.In this section you will learn how to display current date in text box using JavaScript.For this purpose, we have used JavaScript Date object. The getDate() method returns the day of the month (from 1 to 31) , getFullYear() returns the year(four digits) and the getMonth() method returns the month for the current date.The getMonth() method return months from 0 to 11 therefore we have added 1 to the value return from it.
Then we have used document.getElementById() method to access the input element through id attribute and used the value property to store the current date in the textbox.
Here is the code:
<html> <script> function addDate(){ date = new Date(); var month = date.getMonth()+1; var day = date.getDate(); var year = date.getFullYear(); if (document.getElementById('datetext').value == ''){ document.getElementById('datetext').value = day + '-' + month + '-' + year; } } </script> <body onload="addDate();"> Today's Date is: <input type="text" id="datetext"> </body> </html> |
Output: