views:

34

answers:

2

I need to be able to set an input field to a date 365 days from the current date. This field sets the expiration date of a membership purchase. I have this javascript which does not work for some reason.

<input type="text" name="ZoneExpiry" id="ExpiryDate" />
<script type="text/javascript">
function setExpiryDate( )
{
var dat=new Date();
dat.setDate(dat.getDate() + 45);
var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun",   "Jul","Aug","Sep","Oct","Nov","Dec")
var pretty = dat.getDate() + "-" + monthname[dat.getMonth()] + "-" + dat.getFullYear();    
document.getElementById("ExpiryDate").value = pretty;
}
</script>

I'm no javascript expert but for some reason this is not setting the input field to the proper value.

Is there a way to fix this javascript or accomplish a similar task using jQuery?

The date format needs to be 01-Jan-2010, so day-month-4digit year.

Thanks for any help!

A: 

This works fine for me. The only thing that seems to be wrong is that you are adding 45 days to the current date rather than 365.

lonesomeday
When I preview the code in my browser, the text field is empty. Nothing shows. The 45 days glitch is my error. Forgot to update that code. Where are you seeing it work? Sorry for basic questions, I'm not that familiar with javascript.
mmsa
How are you invoking your Javascript function? Is there a `onclick` handler somewhere?
lonesomeday
It needs to run on page load. The field will eventually be hidden so the script needs to run automatically? Is that the problem?
mmsa
A: 

with jQuery:

    <input type="text" name="ZoneExpiry" id="ExpiryDate" />
    <script type="text/javascript">
    $.fn.setExpiryDate = function(expirationDay) {
       var dat = new Date(),
           pretty = 0,
           monthname = new Array("Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec");

       dat.setDate(dat.getDate() + expirationDay);

       pretty = dat.getDate() + "-" + monthname[dat.getMonth()] + "-" + dat.getFullYear();

       $(this).val(pretty);
    }

    $('#ExpiryDate').setExpiryDate(365);
    ​</script>
andres descalzo
Andres, thanks! This works perfectly!!
mmsa
@andres This should be in `$(document).ready()`
lonesomeday
yes, for this function only has to be loaded "ExpiryDate". Can be in '$(document).ready(...)' or like this in the example after "ExpiryDate"
andres descalzo