Period filtering in data type inputs

Asked

Viewed 1,360 times

4

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

I was using the attributes min and max for testing, as they are fixed values, and worked:

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

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

  • The question is unclear to me. You mean an input type date with calendar (HTML5) and you want to limit the possible choice of dates to max 3 months before the current day?

  • What is the calendar plugin you’re using? Post an example of code to help! xD

  • That. Follow the example. Date: <input type="date" name="dateIni" min="2013-12-01" max="local">

  • Just to be clear, you want when loading the page the min be set to data_atual - 3 meses?

  • Yes and max the date today.

  • I did an update to the code. Was that the function you wanted? Works for me in Chrome.

Show 1 more comment

1 answer

2


Try it like 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();

Example

Bear in mind that input type date is +/- recent (HTML5) and that many browsers do not recognize this tag. Perhaps it is best to use a library that has a separate Picker date.

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

  • @Haonenakano, this script reads the current day date and removes 3 months. Then applies the date to the input

Browser other questions tagged

You are not signed in. Login or sign up in order to post.