[英]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. 我想在用户点击某些文本时使用jQuery显示一个datepicker,并且在用户选择datepicker上的日期之后,我可以将日期选择器中的值作为javascript变量获取。 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. 问题是当datepicker弹出时,当我试图在datepicker弹出窗口上选择日期时,它不会关闭datepicker弹出窗口。
You can use datepicker's onSelect
option: 您可以使用datepicker的
onSelect
选项:
Called when the datepicker is selected.
选择日期选择器时调用。 The function receives the selected date as text and the datepicker instance as parameters.
该函数接收所选日期作为文本,并将datepicker实例作为参数接收。
Then you can use jQuery hide()
. 然后你可以使用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>
Please find below the altered 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();
}
}
);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.