Hiding jquery datepicker when clicking on button

Viewed 2860

I have a jquery datepicker and the problem I'm having is I want to be able to toggle the datepicker to open and close when the button/textfield is clicked, but right now I have to either select a day or click outside of the calendar (somewhere on the screen) to close the datepicker. I want to open and close it by pressing and pressing again (toggle) on the same button to open and close it.

FYI - I know there's a hide method for datepicker but not sure if that will work here

Here is link to the Fiddle and some code below

$('#date1').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: "m/d/yy"
});
#ui-datepicker-div { font-size: 12px; } 
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Date Picker on input field: <input type="text" id="date1" name="date1"/> <br/>

1 Answers

Try:

$('#date1').click(function(e) {
  if ($(this).data('count')) { // toggle
    if ($('#ui-datepicker-div').is(':visible')){
         $('#date1').datepicker('hide');
    } else {
            $('#date1').datepicker('show');
    }
   } else { // first click
     $(this).data('count', 1);
  }
});
$('#date1').blur(function() {
  $(this).data('count', '')
});

 $('#date1').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: "m/d/yy"
});
#ui-datepicker-div { 
    font-size: 12px; 
    position: relative !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

Date Picker on input field: <input type="text" id="date1" name="date1"/> <br/>

Related