我有一个JS代码,当你改变一个字段,它调用搜索例程。问题是,当Datepicker更新输入字段时,我找不到任何将触发的jQuery事件。
由于某种原因,当Datepicker更新字段时,没有调用更改事件。当日历弹出时,它会改变焦点,所以我也不能使用它。什么好主意吗?
我有一个JS代码,当你改变一个字段,它调用搜索例程。问题是,当Datepicker更新输入字段时,我找不到任何将触发的jQuery事件。
由于某种原因,当Datepicker更新字段时,没有调用更改事件。当日历弹出时,它会改变焦点,所以我也不能使用它。什么好主意吗?
当前回答
T.J.克劳德(T.J. Crowder)的答案(https://stackoverflow.com/a/6471992/481154)非常好,而且仍然很准确。在onSelect函数中触发更改事件是最接近的方法。
然而,在datepicker对象(lastVal)上有一个很好的属性,它允许你只在实际更改时有条件地触发更改事件,而不必自己存储值:
$('#dateInput').datepicker({
onSelect: function(d,i){
if(d !== i.lastVal){
$(this).change();
}
}
});
然后像往常一样处理更改事件:
$('#dateInput').change(function(){
//Change code!
});
其他回答
我认为你的问题可能在于你的约会选择器的设置。 你为什么不断开输入…不要使用altField。相反,当onSelect触发时显式地设置值。这将让你能够控制每一次互动;用户文本字段和datepicker。
注意:有时你必须在.change()而不是.onSelect()上调用例程,因为onSelect可以在你不期望的不同交互上调用。
伪代码:
$('#date').datepicker({
//altField: , //do not use
onSelect: function(date){
$('#date').val(date); //Set my textbox value
//Do your search routine
},
}).change(function(){
//Or do it here...
});
$('#date').change(function(){
var thisDate = $(this).val();
if(isValidDate(thisDate)){
$('#date').datepicker('setDate', thisDate); //Set my datepicker value
//Do your search routine
});
});
在jQueryUi 1.9上,我已经设法让它通过一个额外的数据值和beforeShow和onSelect函数的组合来工作:
$( ".datepicker" ).datepicker({
beforeShow: function( el ){
// set the current value before showing the widget
$(this).data('previous', $(el).val() );
},
onSelect: function( newText ){
// compare the new value to the previous one
if( $(this).data('previous') != newText ){
// do whatever has to be done, e.g. log it to console
console.log( 'changed to: ' + newText );
}
}
});
对我有用:)
我的soluthion:
var $dateInput = $('#dateInput');
$dateInput.datepicker({
onSelect: function(f,d,i){
if(d !== i.lastVal){
$dateInput.trigger("change");
}
}
}).data('datepicker');
$dateInput.on("change", function () {
//your code
});
如果你正在使用wdcalendar,这将帮助你
$("#PatientBirthday").datepicker({
picker: "<button class='calpick'></button>",
onReturn:function(d){
var today = new Date();
var birthDate = d;
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
$('#ageshow')[0].innerHTML="Age: "+age;
$("#PatientBirthday").val((d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear());
}
});
事件onReturn为我工作
希望这对你有所帮助
试一试:
$('#idPicker').on('changeDate', function() {
var date = $('#idPicker').datepicker('getFormattedDate');
});