Search code examples
javascripthtmlhref

How to insert a <script> html attribute as part of url of a href html attribute


I have the following code:

<!DOCTYPE html>
<html>
 <body>
  <table border="1">
   <tr>
    <td >row 2, cell 1</td>
    <td style="white-space:nowrap;"><a href="http://aa.bb.cc/<script type="text/javascript"><!--
     var date = new Date();
     var d  = date.getDate();
     var day = (d < 10) ? '0' + d : d;
     var m = date.getMonth() + 1;
     var month = (m < 10) ? '0' + m : m;
     var yy = date.getYear();
     var year = (yy < 1000) ? yy + 1900 : yy;
     document.write( year + month + day);
     //--></script>>  Click to check</a></td>
   </tr>
  </table> 
 </body>
</html>

What I want is that when I press :click, the browser should go to the following link: http://aa.bb.cc/yyyymmdd

yymmmdd is obtained through the Javascript and displays the current year, month date.

The Javasript works, but I can't add the result of it to the URL of the a href attribute.


Solution

  • Why not separate your javascript from your html, by putting it into the head element. Then once the document has loaded onload call that function to append it to your links href.

    <!DOCTYPE html>
    <html>
    <head>
    <script  type="text/javascript">
    function appendDateToURL(){
      var date = new Date();
      var d  = date.getDate();
      var day = (d < 10) ? '0' + d : d;
      var m = date.getMonth() + 1;
      var month = (m < 10) ? '0' + m : m;
      var yy = date.getYear();
      var year = (yy < 1000) ? yy + 1900 : yy;
      var myLink = document.getElementById("myLink");
      myLink.setAttribute("href",(myLink.href+ year + month + day));
    }
    </script>
    </head>
    <body onload="appendDateToURL();">
    <table border="1">
    <tr>
    <td >row 2, cell 1</td>
    <td style="white-space:nowrap;"><a id="myLink" href="http://aa.bb.cc/">  Click to check</a></td>
    </tr>
    </table> 
    </body>