views:

605

answers:

2

Hi, I need to populate a text box with a calculated date and can't get the calculated value to appear. e.g. the text box should default to today's date + 5 days. I have java script doing the calculations and they are working, and I know that I use the "value" attribute for the text box but am unsure as to the syntax to parse the java script var to the value attribute.

var currentTime = new Date()
var day = currentTime.getDate() +5
var year = currentTime.getFullYear()
var month = currentTime.getMonth() + 1;
var calcdate = day + "/" + month + "/" + year;

<input type="text" name="T1" size="20" id="sub_date" value="<document.write(subdate)">
+2  A: 
document.getElementById('sub_date').value(calcdate);

or something like that

Aneurysm9
+2  A: 

Hi Dave,

I would probably start by taking your calcdate (and associated variables) and sticking that in a function:

function calculate_date() {
  currentTime = new Date();
  day         = currentTime.getDate() + 5;
  year        = currentTime.getFullYear();
  month       = currentTime.getMonth() + 1;
  calcdate    = day + "/" + month + "/" + year;
  return calcdate;
}

We can set up another small function which will actually insert the date in the desired element:

function prepopulate_date() {
  document.getElementById("sub_date").setAttribute('value', calculate_date());
}

The above does the same as what you wanted to do earlier, but in a slightly cleaner way.

Lastly, we need to actually call this function. So far, we've only set up the functions to do the work for us, we haven't actually told them to run. On top of that, we need to make sure the element actually 'exists' before we try inserting anything into it. A common problem, if you don't do this on the load or 'ready' event (an event that, as far as I know, you only get when using external javascript libraries), is that you will try inserting a value into an element that doesn't yet exist because the browser hasn't had the time to load the entire html contents of the page. So we can do something as follows:

window.onload = prepopulate_date;

If you'd like, you can download an example.

I hope this helps. Cheers.

theIV
Awesome works like a treat. Thank-you very much for not only the solution but the excellent explanation.Cheers,Dave