Lewis Pye February 2016

displaying current date in a text box - javascript

I am having great difficulty getting the current date to be inputted into a text box within a form i am creating as a default value. at the moment i have the following code, which i believe creates the current date, followed by the text box code which i am unsure on how to modify in order for the date to be displayed inside.

function getDate(){
 var todaydate = new Date();
 var day = todaydate.getDate();
 var month = todaydate.getMonth() + 1;
 var year = todaydate.getFullYear();
 var datestring = day + "/" + month + "/" + year;
 document.getElementById("frmDate").value = datestring();
} 
<input type="text" name="frmDateReg" required id="frmDate"  value="getDate()">

if anyone could suggest how to create todays date and input it into the textbox as default it would be greatly appreciated. (Please excuse any format issues as i am new to stack overflow) Thanks

Answers


durbnpoisn February 2016

You've got the right idea. It's just out of order:

<input type="text" name="frmDateReg" required id="frmDate" value="">

function getDate(){
   var todaydate = new Date();
   var day = todaydate.getDate();
   var month = todaydate.getMonth() + 1;
   var year = todaydate.getFullYear();
   var datestring = day + "/" + month + "/" + year;
   document.getElementById("frmDate").value = datestring;
  } 
getDate(); 

Your code is correct, except that adding the function call in the value doesn't do anything. You need something else to trigger the function. The way I have it there, it will execute automatically when the page loads.

Aslo, datestring is not a function. It's just a variable. So you can leave off the ()


Thirupaa February 2016

<html>
<body onload="myFunction()">
Date: <input type="text" id="demo"/>
<script>
function myFunction() {
document.getElementById('demo').value= Date();
}
</script>
</body>
</html>

Use this code. this will helpful


Kirill kilo-code Babkin February 2016

<input type="text" name="frmDateReg" required id="frmDate"  >


<script>
function getDate(){
var todaydate = new Date();
var day = todaydate.getDate();
var month = todaydate.getMonth() + 1;
var year = todaydate.getFullYear();
var datestring = day + "/" + month + "/" + year;
document.getElementById("frmDate").value = datestring; //don't need ()
}

document.getElementById("frmDate").onload = getDate(); 
</script>

Post Status

Asked in February 2016
Viewed 1,853 times
Voted 6
Answered 3 times

Search




Leave an answer