【问题标题】:HOW to get the Year from a <input type= "date"/> using getFullYear()如何使用 getFullYear() 从 <input type= \"date\"/> 获取年份
【发布时间】:2022-10-15 00:54:14
【问题描述】:

我试图通过从用户的出生年份中减去当前年份来计算用户的年龄,但出现此错误:

未捕获的类型错误:birthDate.value.getFullYear 不是函数

这是我的鳕鱼

function checkAge(){
            let birthDate = document.getElementById("dateOfBirth");
            let today = new Date();
            let userage = today.getFullYear() - birthDate.value.getFullYear();
<label for="dateOfBirth">Date of Birth<strong>*</strong></label>
            <input type="date" id="dateOfBirth" name="D.O.B" >

e:

【问题讨论】:

  • 您的示例中没有任何内容调用您的函数。您还尝试在字符串上调用 Date() 函数。
  • birthDate.valueAsDate?
  • @evolutionxbox 非常感谢它现在正在工作

标签: javascript validation user-input


【解决方案1】:

birthDate.value 将返回一个字符串,试试这个:

function checkAge(){
     let birthDate = document.getElementById("dateOfBirth");
     let today = new Date();
     let userage = today.getFullYear() - new Date(birthDate.value).getFullYear();

【讨论】:

    猜你喜欢
    • 2022-12-07
    • 2016-01-23
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    相关资源
    最近更新 更多