javascripthtmljquerydatepickerjquery-ui-datepicker

Can I hide the jQuery UI datepicker only when clicking on the datepicker's input field in the DOM?


I have a jQuery UI datepicker and the problem I'm having is I want to be able to toggle the datepicker to open and close when the button/text field 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.

I know there's a hide method for datepicker, but I'm not sure if that will work here.

Here is link to a JSFiddle and the code below

$('#date1').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: "m/d/yy"
});
#ui-datepicker-div { font-size: 12px; } 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/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/>


Solution

  • 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/>