简体   繁体   中英

Dynamically update expiry date based on a previous date using JavaScript

I want supply the effective date(initial date) and the system automatically add one(1) year to the date supplied above, using JavaScript or any other better method.

<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
    <p>
        <strong style="color:black">Software Name:</strong>
        <input type="text" name="swname" value=""  />
    </p>&nbsp;

    <p>
        <strong style="color:black"> 
            Company 
            <input type="text" name="coy" size="50" value="">
        </strong>
    </p>&nbsp;

    <p>
        <strong style="color:black"> 
            Effective Date 
            <input type="date" name="sdate" value="" onblur="getYearVal();" />
        </strong>
    </p>&nbsp;

    <script>
        function getYearVal() {
            //script that automatically add one year to the above is placed here
        }
    </script>

    <p>    
        <strong style="color:black"> 
            Expiry Date
            <input type="date" name="edate"  id="edate"  value=""/>
        </strong>

        <input type="submit" name="submit" value="Register " /> | 
        <input type="reset" name="reset" value="Cancel" /> 

</form>

First you have to create a Date object .

var date = new Date('year','month','day');

Then add 1 year:

date.setFullYear(date.getFullYear() + 1);

This is just an example, modify it according to your needs.

I believe what you are looking for is the getFullYear() js function

var d = new Date();
var n = d.getFullYear(); 

source here: http://www.w3schools.com/jsref/jsref_getfullyear.asp

If you want to set a value to input you should at least select it. Here you can use either getElementById or querySelector

To set a value of element just use value propery

And finally check out Date javascript object

code that should do things:

 <form action="" method="post"> <p><strong style="color:black">Software Name:</strong> <input type="text" name="swname" value="" /> </p> <p><strong style="color:black">Company</strong> <input type="text" name="coy" size="50" value=""> </p> <p><strong style="color:black">Effective Date</strong> <input type="date" name="sdate" value="" /> </p> <p><strong style="color:black">Expiry Date</strong> <input type="date" name="edate" id="edate" value="" /> </p> <p> <input type="submit" name="submit" value="Register " />| <input type="reset" name="reset" value="Cancel" /> </p> <script> var date = new Date(), dateString = (date.getFullYear() + 1) + '/' + (date.getMonth() + 1) + '/' + date.getDate(); document.querySelector('input[name="sdate"]').value = dateString; </script> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM