Assign jQuery datepicker to div element and get value

I want to show datepicker using jQuery when the user clicks on some text, and after the user selects a date on datepicker, I can get the value from the date selection as a javascript variable. My code is as follows:

<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 that the datepicker popup when I tried to select a date on the datepicker popup will not close the datepicker popup.

Script example

+5
source share
2 answers

You can use the datepicker onSelect parameter:

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

Then you can use jQuery hide() .

Here's a living 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> 
+1
source

The following is the modified code:

 $(document).ready(function() { var selectedDate; $("#show-datepicker").click(function(){ $("#datepicker-container").show(); }); $('#select-delivery-date-input').datepicker({ dateFormat:'yy-m-d', minDate: new Date(), onSelect: function(date){ selectedDate = date; alert(selectedDate);//selected date is assigned to date1, you can use date1 anywhere $("#datepicker-container").hide(); } } ); }); 
0
source

Source: https://habr.com/ru/post/1273425/


All Articles