HTML:
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="click to show datepicker" id="example1">
</div>
</div>
jQuery:
<script type="text/javascript">
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
我使用 Bootstrap 日期选择器。
当我单击日期选择器时,它会打开并选择任何日期。
我的问题:
If I choose date from datepicker, I want to close datepicker popup.
我需要使用哪个事件才能在选定日期关闭日期选择器?
已编辑:
我找到了解决办法
这有效
$(document).mouseup(function (e) {
$('#example1').Close();
});
但是下面不起作用,为什么?
$('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
最佳答案
实际上你不需要全部替换(@Ben Rhouma Zied answere)....
有两种方法可以做到这一点。一种是使用 autoclose 属性,另一种(替代)方法是使用选择日期时输入触发的 on Change 属性。
HTML
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div>
jQuery
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});
这就是你所要做的:)
<强> HERE IS A FIDDLE 看看发生了什么。
2016 年 7 月 13 日的 Fiddle 更新:CDN 不再存在
根据您的编辑:
$('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
在这里,您获取输入(没有 Close-Function)并创建一个 Datepicker-Element。如果元素发生变化,您想关闭它,但仍然尝试关闭输入(没有关闭功能)。
Binding a mouseup event to the document state may not be the best idea because you will fire all containing scripts on each click!
就是这样:)
编辑:2017 年 8 月(添加了 StackOverFlowFiddle 又名代码片段。与帖子顶部相同)
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});
.hero-unit{
float: left;
width: 210px;
margin-right: 25px;
}
.hero-unit input{
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div>
编辑:2018 年 12 月 显然 Bootstrap-Datepicker 不适用于 jQuery 3.x see this to fix
关于javascript - jQuery Datepicker 在选定日期后关闭日期选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24040165/