开发者

Setting a field to a date in the future using jQuery or Javascript

开发者 https://www.devze.com 2023-01-19 11:24 出处:网络
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 reas

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();
da开发者_运维问答t.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!


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>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消