0
votes

I have a form that takes a user's date of birth. The problem with just using a datepicker popup to get year, month, and date, is that it can take forever to go through years, as the interface only goes month by month.

So, the current solution is to have one field for the year, using HTML5 number field, so a user can easily scroll through years, and then have another field that uses a datepicker popup to pick the month and day. People seem to like picking dates with the calendar popup.

In the form I have, the user can select the year and the month/day separately, and that's all fine. The datepicker defaults to showing the months and dates for the current year, but in a sense, this doesn't matter. We don't need to record what day of the week any one date lands on, so it doesn't matter if they select January 27th, for example, from 2014, even if their year of birth is 1980, because what we get back in the post data is 1980 and 01-27, which we combine to 1980-01-27, and we store that in the database.

Even though it's working, I'm pedantic, and it bugs me to show the calendar from the current year even through the user may have entered a different year. So, what I want to do is make it so that the year in the datepicker changes to match the year in the year field.

I'm stuck because the code for datepicker is a bit obscure to me, and I'm not sure how to take the value of the year field and apply it. I think what I need is an onchange Javascript event in the year field, but what function would I apply so as to make the datepicker adjust accordingly?

JSFiddle is here. And this is the code:

<form>
    <ul>
        <li>  
            <label for="birthday">Date of birth</label>
            <input name="birthyear" type="number" min="1920" max="2002" step="1" value="1980" class="number" required />
            <input name="birthday" type="date" id="birthday" placeholder="MM-DD" required />
        </li>
    </ul>
</form>

    <script type="text/javascript">
if ( $('#birthday')[0].type != 'date' ) $('#birthday').datepicker({ dateFormat: 'mm-dd' });
</script>
1
Could you be a little more specific about "So, what I want to do is make it so that the year in the datepicker changes to match the year in the year field."? Use the actual element IDs if you must.DevlshOne

1 Answers

1
votes

This may not be EXACTLY what you're trying to do, but it certainly fixes your problem of having to scroll through months and months trying to achieve the correct year by changing it to a dropdown.

Datepicker changeYear option

HTML

<form>
    <ul>
        <li>
            <label for="birthday">Date of birth</label>
            <input name="birthday" id="birthday" placeholder="mm/dd/yyyy" required />
        </li>
    </ul>
</form>

JS

$(function () {
    $('#birthday').datepicker({
        dateFormat:'mm/dd/yy',
        changeYear:true,
        yearRange:'c-80:c+0'
    });
});

Resulting Datepicker Dialog Box

enter image description here