Reputation: 117
Hi in the below code how to display after selecting the date of birth I want to show the age. My expected output is the above screen shot. Now when I am selecting date of birth nothing was happening.
html
<input type="text" name="date_birth1" class="login-input" placeholder="Date Of Birth" id="datepicker11" autofocus>
<input type="text" name="age" id="age" pattern = "^\D{0,100}$" class="login-input" placeholder="Age" Onchange="return findage();" autofocus >
javascript
function findage() {
var PresentDay = new Date();
var dateOfBirth = (new Date(document.getElementById("datepicker11").value));
var months = (PresentDay.getMonth() - dateOfBirth.getMonth() +
(12 * (PresentDay.getFullYear() - dateOfBirth.getFullYear())));
document.getElementById("age").value = Math.round(months / 12);
}
Upvotes: 0
Views: 176
Reputation: 114
You should put the onchange event on the date of birth input box not on the age one.
The onchange event will be called when you change the date of birth after you lose focus from that box.
here i have changed it for you
<input type="text" name="date_birth1" class="login-input" placeholder="Date Of Birth" id="datepicker11" onchange="findage();" autofocus>
<input type="text" name="age" id="age" pattern = "^\D{0,100}$" class="login-input" placeholder="Age" autofocus >
Hope this helps you
Upvotes: 1
Reputation: 32145
You are not firing any event with your birth date field, because you are using Onchange
instead of onchange
and you are using it with the age text field call it in the datepicker instead, this is the working code :
function findage() {
var PresentDay = new Date();
var dateOfBirth = (new Date(document.getElementById("datepicker11").value));
var months = (PresentDay.getMonth() - dateOfBirth.getMonth() +
(12 * (PresentDay.getFullYear() - dateOfBirth.getFullYear())));
document.getElementById("age").value = Math.round(months / 12);
alert(Math.round(months / 12));
}
<input type="text" name="date_birth1" class="login-input" placeholder="Date Of Birth" id="datepicker11" onchange="findage();" autofocus>
<input type="text" name="age" id="age" pattern = "^\D{0,100}$" class="login-input" placeholder="Age" >
Upvotes: 1
Reputation: 2255
Onchange="return findage();"
This should be in the first input, not the second!
Upvotes: 1