简体   繁体   English

根据未使用JavaScript显示的出生日期

[英]based on date of birth age not displaying using javascript

当我选择出生日期时,我想显示年龄

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 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 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);
            }
Onchange="return findage();"

这应该在第一个输入中,而不是第二个中!

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 : 您不会在出生日期字段中触发任何事件,因为您使用的是Onchange而不是onchange ,并且使用的是age文本字段,请在Onchange调用它,这是工作代码:

 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" > 

You should put the onchange event on the date of birth input box not on the age one. 您应该将onchange事件放在出生日期输入框上,而不要在第一年龄上。

The onchange event will be called when you change the date of birth after you lose focus from that box. 当您从该框失去焦点后更改出生日期时,将调用onchange事件。

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 希望这对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM