0

I have a form that contains a date field and a other empty div:

<input type="date" name="b_day" id="b_day" />
<div id="age"></div>

I want after a visitor fills the field the div age to look something like "10.5 yo" calculating the difference in years-months from today, without refreshing the page

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
theok
  • 121
  • 9
  • You can do this direct in javascript or (if you really want to send the information to PHP) send this info with AJAX. Did you tried something like this? I think that your question is too broad. – James Jun 24 '15 at 20:07
  • Ajax will work better for me but what would be the proper syntax to call the php script that I have ready and works fine – theok Jun 24 '15 at 20:24
  • 1
    read http://stackoverflow.com/help/how-to-ask. do more research. – Yogesh Mangaj Jun 24 '15 at 20:25
  • @Yogesh, In order for me to ask a question means that I already done my research and if I was a super developer I wound need any help. Thanks for the recommendation... I will do so. In the mean time your knowledge is what I need – theok Jun 24 '15 at 20:46
  • 1
    If you've done your research, what did you try? – Populus Jun 24 '15 at 21:13
  • possible duplicate of [Calculate age in JavaScript](http://stackoverflow.com/questions/4060004/calculate-age-in-javascript) – Yogesh Mangaj Jun 26 '15 at 13:03

1 Answers1

0

You can do it with JavaScript, making use of its Date object. I'd probably end up with something like this:

HTML:

<input type="date" name="b_day" id="b_day" onchange="calculateAge()" />
<div id="age"></div>

JavaScript:

function calculateAge() {
  var b_day = new Date(document.getElementById('b_day').value);
  var today = new Date();
  var age = (today.getFullYear() - b_day.getFullYear()) + (((today.getMonth() + 1) - (b_day.getMonth() + 1)) / 12);

  document.getElementById('age').innerHTML = age;
}

Note that in JavaScript's Date the months go from 0 to 11, hence the addition of one.

harris
  • 251
  • 3
  • 12