简体   繁体   English

在javascript中输入日期,检测是否选择了年,月或日

[英]Date input in javascript, detect if year, month or day was selected

Is it possible to detect event on different parts of an input date field. 是否有可能在输入日期字段的不同部分检测事件。

<input type="date" value="2018-08-15">

In other words did the user select the year, the month or the day(in this specific scenario). 换句话说,用户是否选择了年,月或日(在此特定方案中)。

You could use .split. 您可以使用.split。 Start at 0, then use a regex to separate user input at slashes. 从0开始,然后使用正则表达式以斜杠分隔用户输入。 Now you can check each array index for a value other than the default. 现在,您可以检查每个数组索引的默认值以外的其他值。

Something like this. 这样的事情。 (untested) (另)

var d = document.getElementById('date').value;
var dArray = d.split(0, /\//);
for (var i = 0; i < i.length; i++;) {
    if ((dArray[i] === 'mm') || (dArray[i] === 'dd') || (dArray[i] === 'yyyy') { 
        // date incomplete
    }
}

Note: the date element doesn't have full browser support yet. 注意:date元素还没有完全的浏览器支持。

Unfortunately the date element refuses to give incomplete data ( value returns nothing if the date is incomplete), but when it is complete we can simply check for changes from the last time it was changed, ignoring the empty arrays. 不幸的是,date元素拒绝提供不完整的数据(如果日期不完整,则value不返回任何value ),但是当它完成时,我们可以简单地检查自上次更改以来的更改,而忽略空数组。

Do notice that the change event only fires on valid input changes (or from valid input to invalid input), so if a part of the date input (date/month/year) is invalid, the others won't trigger change until the invalid part is turned valid (which does trigger change). 请注意, change事件仅在有效输入更改(或从有效输入更改为无效输入)时触发,因此,如果日期输入的一部分(日期/月/年)无效,则其他事件直到无效输入才会触发更改零件变为有效(确实会触发更改)。

 function dateListener(e) { let arr = e.target.value.split('-'); if(!this.prevArr)this.prevArr=[]; if(this.prevArr[0] != arr[0] && arr[0]) { console.log(`The year was changed from ${this.prevArr[0]} to ${arr[0]}`); } if(this.prevArr[1] != arr[1] && arr[1]) { console.log(`The month was changed from ${this.prevArr[1]} to ${arr[1]}`); } if(this.prevArr[2] != arr[2] && arr[2]) { console.log(`The date was changed from ${this.prevArr[2]} to ${arr[2]}`); } if(arr[0]) this.prevArr=arr; //If the date is falsey (undefined/empty string), so is the whole array. }; document.getElementById("datefield").addEventListener("change", dateListener); 
 <input type="date" id="datefield" /> 

What we're doing here is taking advantage of the fact that functions are objects, and settings a variable on the function to save the previous state of the input. 我们在这里利用的是函数是对象这一事实,并在函数上设置变量以保存输入的先前状态。 Of course we don't have to do that and we could create a variable that's not bound to the function to save that date, but I chose to do this because of comfortability. 当然,我们不必这样做,我们可以创建一个不与该函数绑定的变量来保存该日期,但是出于舒适性的考虑,我选择这样做。

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

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