Javascript – How to call a javascript function from a table in HTML

html, javascript, jquery

I'm new to Javascript and HTML. Now, I'm using HTML to display a time retrieved from XML file. Below is the HTML tags.

<tr>  <th>Date of Birth: </th>  <td>{{dob}}</td></tr>      

This will display the date in yyyy-mm-dd .i.e date will be displayed as 2012-03-12 I want this to be displayed as 12 Mar 2013. I used moment.min.js but was not successfull. I don't know how to call a javascript function from tags and get the date displayed accordingly.

Best Solution

<table>  <tr>    <th>Date of Birth: </th>    <td id='date-of-birth'></td>  </tr></table> <script src="http://momentjs.com/downloads/moment.min.js"></script><script>  var dob = '2012-03-12';  var dateString = moment(dob).format('DD MMMM YYYY');  var element = document.getElementById('date-of-birth');  element.innerHTML = dateString;</script>

Fiddle.

However, if you want to use the {{variable}} bracket syntax for inserting values into your HTML, you can use a JavaScript templating library like Handlebars.

Here's an example:

<script id="sample-template" type="text/x-handlebars-template">  <table>    <tr>      <th>Date of Birth: </th>      <td>{{dob}}</td>    </tr>  </table></script><div id="output"></div><script src="//code.jquery.com/jquery-1.10.2.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.1.2/handlebars.min.js"></script><script src="http://momentjs.com/downloads/moment.min.js"></script><script>  var dob = '2012-03-12';  var dateString = moment(dob).format('DD MMMM YYYY');  var source = $('#sample-template').html();  var template = Handlebars.compile(source);  $('#output').html(template({dob: dateString}));</script>

Fiddle. (Edit: Wrong link. Fixed.)