Period-based filtering on data type inputs

Posted on

Question :

I have a system where I have a <input type="date"> and I need to filter it, to bring in the calendar only the dates of 3 months ago and the current month

I was using the attributes min and max to test, since they are fixed values, and it worked:

<input type="date" name="dateIni" min="2013-12-01" max="local">

However, I need to manually change every time I see the month. How to automate this?


Answer :

Try this:

function decimas(n){
    return n > 9 ? "" + n: "0" + n;
function getDate(m) {
    var data = new Date();
    var diffAno = 0;
    var mesAnterior = data.getMonth() - (m === undefined ? 1 : m - 1);
    if (mesAnterior < 1) {
        mesAnterior = mesAnterior + 12;
        diffAno = -1;
    mesAnterior = decimas(mesAnterior);
    var diaAnterior = decimas(data.getDate());
    return (data.getFullYear() + diffAno) + '-' + mesAnterior + '-' + diaAnterior;

document.querySelector('input[name=dateIni]').setAttribute("min", getDate(3));
document.querySelector('input[name=dateIni]').valueAsDate  = new Date();


Note that input type date is +/- recent (HTML5) and many browsers do not recognize this tag. Maybe better to use a bible library that has a separate date picker.

I added the decimas() function because the W3C recommendation is to use two digits on the date.


Leave a Reply

Your email address will not be published. Required fields are marked *