Web Analytics Made Easy -
StatCounter How can I populate a form field with a date generated by javascript code? - CodingForum

Announcement

Collapse
No announcement yet.

How can I populate a form field with a date generated by javascript code?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • How can I populate a form field with a date generated by javascript code?

    Hi. I have used this code to generate a date that is 30 days from the current date:

    Code:
    <script type="text/javascript">
    var dat=new Date();
    dat.setDate(dat.getDate() + 30);
    var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec")
    document.write(dat.getDate() + "-")
    document.write(monthname[dat.getMonth()] + "-")
    document.write(dat.getFullYear())
    </script>
    How can I take the generated date/value and use it to populate the "Expiry Date" field on the form of the following page?

    http://coastalselectproperties.matts.../datetest.html

    Thank you for your help - It's greatly appreciated.

  • #2
    If you use document.write, you *must* do it INLINE right as you create the form field.

    Better, in most cases, would be to do:
    Code:
    <script type="text/javascript">
    function setExpiryDate( )
    {
        var dat=new Date();
        dat.setDate(dat.getDate() + 30);
        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>
    Put that in the <head>...</head> of your page and then invoke it via
    Code:
    <body onload="setExpiryDate( )">
    Be yourself. No one else is as qualified.

    Comment


    • #3
      Correction:-

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


      You could also "simulate" document.write() with a div:-

      <div id = "ExpDat"></div>
      and alter the script to read:-
      document.getElementById("ExpDat").innerHTML = "This offer will expire on " + pretty;



      We dispense with accuracy - Sign in chemist's shop.
      Last edited by Philip M; Apr 15, 2009, 04:35 AM.

      All the code given in this post has been tested and is intended to address the question asked.
      Unless stated otherwise it is not just a demonstration.

      Comment


      • #4
        Thank you both!!!

        Old Pendant: Thanks for such a quick reply. It was almost perfect. When I couldn't get it to work I figured it was just me. lol.

        Then, I saw Philip's post and voila.

        I really appreciate both of your help.

        Comment


        • #5
          Sorry...sloppy of me.
          Be yourself. No one else is as qualified.

          Comment

          Working...
          X