views:

35

answers:

1

I have a Datepicker using jqueryui DatePicker.

The behavior requirement is:

  • A User can store a Birthdate for a friend. The User should be able to store a year if known, or select "N/A".

  • If "N/A" is selected, Store the year 1900 in the database and only display the day and month in an input field to the User.

  • The dropdown should start at 1950 but show the past 100 years from current date (<-- this would be icing on the cake, otherwise start at current year and if necessary go back to 1900)

Here's what I got so far, but it's kludgey...and that's an understatement. And for some reason, if the user selects a date, but doesn't alter the year dropdown, then the current year is stored, rather than 1900.

(it's in the context of a json call). Surely there's a better way.

var birthday_options = {changeMonth: true, changeYear: true, yearRange: '1900:2010',
        onClose: function(dateText, inst) {
        contact.field_updater('birthday').call(this);
        $('input.mng-birthday').val(function(i, val) {
                       return val.replace('/1900', '');
                    });
        },
        beforeShow: function (input) {
                      setTimeout(function () {
                        $('select.ui-datepicker-year option:first').text('N/A');                                                                 
                      }, 1);
                    }},

.find('.mng-birthday').val(data.birthday || 'Unknown')
  .datepicker(birthday_options)
.end(); 
A: 

Click here to see a demo.

When you find yourself out of scope, the jQuery UI source is easy to modify. You just need to change the function definition for _generateMonthYearHeader:

// StackOverflow question: Add option for N/A
html += '<option value="1900">N/A</option>';

And make this change to _selectDay to ommit the year when N/A is selected.

// StackOverflow question: format the date
if (inst.currentYear == 1900)
    this._selectDate(id, (inst.currentMonth + 1) + "/" + inst.currentDay);
else
    this._selectDate(id, this._formatDate(inst, inst.currentDay,
                     inst.currentMonth, inst.currentYear));

In the script panel you have the core UI script, the modified datpicker script, and the setup:

$(document).ready(function() {
    var year = new Date().getFullYear();

    $(".mng-birthday").datepicker({
        changeYear: true,
        // The year range is from the current year to 100 years before
        yearRange: (year - 100) + ":" + year,
        // The default date is january 1st fifty years before the current year
        defaultDate: "01/01/1900"
    });
});
Ed Saito
I see how this should work, and obviously does on the demo, however i continue to get the year 2016 when I select N/A.
kinet