Yasir Ijaz
Yasir Ijaz

Reputation: 1043

jquery datepicker onselect year

I am selecting only year from drop down. Here is my code:

$('#year1').datepicker( {
    changeMonth: false,
    changeYear: true,
    showButtonPanel: false,
    dateFormat: 'yy',
    yearRange: "-2:+0",
    onClose: function(dateText, inst) { 
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, 1, 1));
    }
});

Now I want to close the panel when I select year from drop down. But it does not close on selecting year. But when I click anywhere else it gets closed. I tried onSelect insted of onClose event but this event does not fire on selecting year. I think this event fires on selecting date. Can anyone help me close it when I select only year from down down. Thanks.

Upvotes: 1

Views: 1800

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

You can use onChangeMonthYear option to run your function when the user selects a year from dropdown. Then you can use hide() method to "close" the picker.

Here a code sample:

$('#year1').datepicker( {
  changeMonth: false,
  changeYear: true,
  showButtonPanel: false,
  dateFormat: 'yy',
  yearRange: "-2:+0",
  onChangeMonthYear: function(year, month, inst){
    // Set date to picker
    $(this).datepicker('setDate', new Date(year, 1, 1));
    // Hide (close) the picker
    $(this).datepicker('hide');
    // Blur to let the picker open on focus in
    $(this).blur();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet"/>

<input type="text" id="year1">

Upvotes: 1

Related Questions