Share on Google+Share on Google+

Display current date in text box in JSP using javascript

Advertisement
In this section you will learn how to display current date in text box using JavaScript.

Display current date in text box in JSP 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:

Advertisements

Posted on: January 9, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.