Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign jQuery datepicker to div element and get the value

I want to show a datepicker using jQuery when user click on some text, and after the user select the date on datepicker, I can get the value from the date picker as javascript variable. My code is like this:

<div id="datepicker-container" style="display: none;">
    <div id="select-delivery-date-input"> </div>
</div>
<a id="show-datepicker">Select Delivery Date</a>
<script>
  $("#show-datepicker").click(function(){
      $("#datepicker-container").show();
  });
  $('#select-delivery-date-input').datepicker({ 
      dateFormat:'yy-m-d',
      minDate: new Date(),
  });
</script>

The problem is when the datepicker popup, when I tried to select the date on datepicker popup it won't close the datepicker popup.

Fiddle example

like image 254
Shell Suite Avatar asked Nov 07 '22 14:11

Shell Suite


1 Answers

You can use datepicker's onSelect option:

Called when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters.

Then you can use jQuery hide().

Here a live sample:

$(document).ready(function() {
  $("#show-datepicker").click(function(){ 
    $("#datepicker-container").show();
  });
  $('#select-delivery-date-input').datepicker({ 
    dateFormat:'yy-m-d',
    minDate: new Date(),
    onSelect: function(selectedDate){
      console.log(selectedDate);
      $("#datepicker-container").hide();
    }
  });
});
<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://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

<div id="datepicker-container" style="display: none;">
  <div id="select-delivery-date-input"> </div>
</div>
<a id="show-datepicker">Select Delivery Date</a>
like image 161
VincenzoC Avatar answered Nov 14 '22 22:11

VincenzoC