简体   繁体   中英

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. Start at 0, then use a regex to separate user input at slashes. 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.

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.

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).

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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