jQuery UI Datepicker onchange 事件问题

发布于 2024-11-17 05:00:57 字数 152 浏览 2 评论 0原文

我有一个 JS 代码,当您更改字段时,它会调用搜索例程。问题是我找不到任何在 Datepicker 更新输入字段时触发的 jQuery 事件。

由于某种原因,当 Datepicker 更新字段时不会调用更改事件。当日历弹出时,它会改变焦点,所以我也无法使用它。有什么想法吗?

I have a JS code in which when you change a field it calls a search routine. The problem is that I can't find any jQuery events that will fire when the Datepicker updates the input field.

For some reason, a change event is not called when Datepicker updates the field. When the calendar pops up it changes the focus so I can't use that either. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

谜兔 2024-11-24 05:00:57

您可以使用日期选择器的 onSelect 事件

$(".date").datepicker({
    onSelect: function(dateText) {
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    }
});

实例

$(".date")
.datepicker({
    onSelect: function(dateText) {
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    }
})
.on("change", function() {
    console.log("Got change event from field");
});
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

不幸的是,只要选择日期,即使日期没有更改,onSelect 也会触发。这是日期选择器中的一个设计缺陷:它总是触发 onSelect (即使没有任何更改),并且不会在发生更改时触发底层输入上的任何事件。 (如果您查看该示例的代码,我们正在监听更改,但它们没有被引发。)当事情发生变化时(可能是通常的更改 事件,或者可能是特定于日期选择器的事件)。


当然,如果您愿意,您可以在 input 上触发 change 事件:

$(".date").datepicker({
    onSelect: function() {
        $(this).change();
    }
});

这将在底层 input 上触发 change对于通过 jQuery 连接的任何处理程序。但同样,它总是会触发它。如果您只想触发真正的更改,则必须保存先前的值(可能通过data)并进行比较。

实例

$(".date")
.datepicker({
    onSelect: function(dateText) {
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);
        $(this).change();
    }
})
.on("change", function() {
    console.log("Got change event from field");
});
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

You can use the datepicker's onSelect event.

$(".date").datepicker({
    onSelect: function(dateText) {
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    }
});

Live example:

$(".date")
.datepicker({
    onSelect: function(dateText) {
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    }
})
.on("change", function() {
    console.log("Got change event from field");
});
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

Unfortunately, onSelect fires whenever a date is selected, even if it hasn't changed. This is a design flaw in the datepicker: It always fires onSelect (even if nothing changed), and doesn't fire any event on the underlying input on change. (If you look in the code of that example, we're listening for changes, but they aren't being raised.) It should probably fire an event on the input when things change (possibly the usual change event, or possibly a datepicker-specific one).


If you like, of course, you can make the change event on the input fire:

$(".date").datepicker({
    onSelect: function() {
        $(this).change();
    }
});

That will fire change on the underlying inputfor any handler hooked up via jQuery. But again, it always fires it. If you want to only fire on a real change, you'll have to save the previous value (possibly via data) and compare.

Live example:

$(".date")
.datepicker({
    onSelect: function(dateText) {
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);
        $(this).change();
    }
})
.on("change", function() {
    console.log("Got change event from field");
});
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

夜巴黎 2024-11-24 05:00:57

TJ Crowder 的回答(https://stackoverflow.com/a/6471992/481154)非常好,而且仍然准确。 在 onSelect 函数中触发更改事件已经非常接近了。

但是,日期选择器对象 (lastVal) 上有一个很好的属性,它允许您仅在实际更改时有条件地触发更改事件,而不必自己存储值:

$('#dateInput').datepicker({
     onSelect: function(d,i){
          if(d !== i.lastVal){
              $(this).change();
          }
     }
});

然后只需像平常一样处理更改事件:

$('#dateInput').change(function(){
     //Change code!
});

T.J. Crowder's answer (https://stackoverflow.com/a/6471992/481154) is very good and still remains accurate. Triggering the change event within the onSelect function is as close as you're going to get.

However, there is a nice property on the datepicker object (lastVal) that will allow you to conditionally trigger the change event only on actual changes without having to store the value(s) yourself:

$('#dateInput').datepicker({
     onSelect: function(d,i){
          if(d !== i.lastVal){
              $(this).change();
          }
     }
});

Then just handle change events like normal:

$('#dateInput').change(function(){
     //Change code!
});
温暖的光 2024-11-24 05:00:57

您在 datepicker 对象中寻找 onSelect 事件:

$('.selector').datepicker({
   onSelect: function(dateText, inst) { ... }
});

Your looking for the onSelect event in the datepicker object:

$('.selector').datepicker({
   onSelect: function(dateText, inst) { ... }
});
維他命╮ 2024-11-24 05:00:57
$('#inputfield').change(function() { 
    dosomething();
});
$('#inputfield').change(function() { 
    dosomething();
});
满身野味 2024-11-24 05:00:57

我写这篇文章是因为我需要一个解决方案,仅在日期更改时才触发事件。

这是一个简单的解决方案。每次对话框关闭时,我们都会测试数据是否已更改。如果有,我们会触发自定义事件并重置存储的值。

$('.datetime').datepicker({
    onClose: function(dateText,datePickerInstance) {
        var oldValue = $(this).data('oldValue') || "";
        if (dateText !== oldValue) {
            $(this).data('oldValue',dateText);
            $(this).trigger('dateupdated');
        }
    }
});

现在我们可以为该自定义事件连接处理程序......

$('body').on('dateupdated','.datetime', function(e) {
    // do something
});

I wrote this because I needed a solution to trigger an event only if the date changed.

It is a simple solution. Each time the dialog box closes we test to see if the data has changed. If it has, we trigger a custom event and reset the stored value.

$('.datetime').datepicker({
    onClose: function(dateText,datePickerInstance) {
        var oldValue = $(this).data('oldValue') || "";
        if (dateText !== oldValue) {
            $(this).data('oldValue',dateText);
            $(this).trigger('dateupdated');
        }
    }
});

Now we can hook up handlers for that custom event...

$('body').on('dateupdated','.datetime', function(e) {
    // do something
});
凤舞天涯 2024-11-24 05:00:57

我正在使用 bootstrap-datepicker,以上解决方案都不适合我。这个答案帮助了我..

bootstrap datepicker手动编辑日期或清除日期时,更改日期事件不会触发

这是我应用的内容:

 $('.date-picker').datepicker({
     endDate: new Date(),
     autoclose: true,
 }).on('changeDate', function(ev){
        //my work here
    });

希望这可以帮助其他人。

I am using bootstrap-datepicker and none of above solution worked for me. This answer helped me ..

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

Here is what I applied:

 $('.date-picker').datepicker({
     endDate: new Date(),
     autoclose: true,
 }).on('changeDate', function(ev){
        //my work here
    });

Hope this can help others.

你是年少的欢喜 2024-11-24 05:00:57

尝试 :

$('#idPicker').on('changeDate', function() {
    var date = $('#idPicker').datepicker('getFormattedDate');
});

Try :

$('#idPicker').on('changeDate', function() {
    var date = $('#idPicker').datepicker('getFormattedDate');
});
骄傲 2024-11-24 05:00:57

我知道这是一个老问题。但我无法让 jquery $(this).change() 事件在 onSelect 上正确触发。因此,我采用以下方法通过 vanilla js 触发更改事件。

$('.date').datepicker({
     showOn: 'focus',
     dateFormat: 'mm-dd-yy',
     changeMonth: true,
     changeYear: true,
     onSelect: function() {
         var event;
         if(typeof window.Event == "function"){
             event = new Event('change');
             this.dispatchEvent(event);
         }   else {
             event = document.createEvent('HTMLEvents');
             event.initEvent('change', false, false);
             this.dispatchEvent(event);
         }
     }
});

I know this is an old question. But i couldnt get the jquery $(this).change() event to fire correctly onSelect. So i went with the following approach to fire the change event via vanilla js.

$('.date').datepicker({
     showOn: 'focus',
     dateFormat: 'mm-dd-yy',
     changeMonth: true,
     changeYear: true,
     onSelect: function() {
         var event;
         if(typeof window.Event == "function"){
             event = new Event('change');
             this.dispatchEvent(event);
         }   else {
             event = document.createEvent('HTMLEvents');
             event.initEvent('change', false, false);
             this.dispatchEvent(event);
         }
     }
});
中性美 2024-11-24 05:00:57

试试这个

$('#dateInput').datepicker({
 onSelect: function(){
       $(this).trigger('change');
      }
 }});

希望这有帮助:)

Try this

$('#dateInput').datepicker({
 onSelect: function(){
       $(this).trigger('change');
      }
 }});

Hope this helps:)

流殇 2024-11-24 05:00:57

在 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 );
        }
    }
});

对我有用:)

On jQueryUi 1.9 I've managed to get it to work through an additional data value and a combination of beforeShow and onSelect functions:

$( ".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 );
        }
    }
});

Works for me :)

枉心 2024-11-24 05:00:57

手册说:

apply.daterangepicker: Triggered when the apply button is clicked, or when a predefined range is clicked

所以:

$('#daterange').daterangepicker({
  locale: { cancelLabel: 'Clear' }  
});

$('#daterange').on('apply.daterangepicker', function() {
  alert('worked!');
});

对我有用。

Manual says:

apply.daterangepicker: Triggered when the apply button is clicked, or when a predefined range is clicked

So:

$('#daterange').daterangepicker({
  locale: { cancelLabel: 'Clear' }  
});

$('#daterange').on('apply.daterangepicker', function() {
  alert('worked!');
});

Works for me.

烟─花易冷 2024-11-24 05:00:57

我的解决方案:

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
});

My 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
});
单身情人 2024-11-24 05:00:57

我认为您的问题可能在于您的日期选择器的设置方式。
为什么不断开输入...不要使用 altField。相反,当 onSelect 触发时显式设置值。这将使您能够控制每次交互;用户文本字段和日期选择器。

注意:有时您必须在 .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
    });
});

I think your problem may lie in how your datepicker is setup.
Why don't you disconnect the input... do not use altField. Instead explicitly set the values when the onSelect fires. This will give you control of each interaction; the user text field, and the datepicker.

Note: Sometimes you have to call the routine on .change() and not .onSelect() because onSelect can be called on different interactions that you are not expecting.

Pseudo Code:

$('#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
    });
});
温柔戏命师 2024-11-24 05:00:57

DatePicker选中值改变事件代码如下

/* HTML Part */
<p>Date: <input type="text" id="datepicker"></p>

/* jQuery Part */
$("#datepicker").change(function() {
                selectedDate= $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
                alert(selectedDate);        
            });

DatePicker selected value change event code below

/* HTML Part */
<p>Date: <input type="text" id="datepicker"></p>

/* jQuery Part */
$("#datepicker").change(function() {
                selectedDate= $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
                alert(selectedDate);        
            });
溺ぐ爱和你が 2024-11-24 05:00:57

如果您使用 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 事件对我有用

希望这会有所帮助

if you are using wdcalendar this going to help you

 $("#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());
        }
      }); 

the event onReturn works for me

hope this help

你如我软肋 2024-11-24 05:00:57

我的解决方案是:

events: {
    'apply.daterangepicker #selector': 'function'
}

My solution is:

events: {
    'apply.daterangepicker #selector': 'function'
}
与君绝 2024-11-24 05:00:57

你们中的一些人可能正在使用名为 XDSoft DateTimePicker https://xdsoft.net/ jqplugins/datetimepicker/

那里,更改事件是

onSelectDate: function(){
  alert('change date event);
}

https://xdsoft.net/jqplugins/datetimepicker/#onSelectDate

Some of you may be using something called XDSoft DateTimePicker https://xdsoft.net/jqplugins/datetimepicker/

There, the change event is

onSelectDate: function(){
  alert('change date event);
}

https://xdsoft.net/jqplugins/datetimepicker/#onSelectDate

扶醉桌前 2024-11-24 05:00:57

您可以使用 datepickeronClose 选项并将更改代码放入其中。当 datepicker 模式关闭时触发。我尝试触发更改事件,但这不起作用,因此我将代码放在 onClose 中,并且它起作用了。如果您需要在选择日期时触发,则同样适用于前面提到的 onSelect

$('#el').datepicker({ 
   onClose: function () {
     // code here
   }
});

日期选择器选项 https://api.jqueryui.com/datepicker/

You can use the onClose option for the datepicker and put your change code inside. This triggers when the datepicker modal is closed. I tried to trigger the change event but that wouldn't work so I put my code inside of the onClose instead and it works. The same may work for onSelect that was mentioned if you need to trigger when the date is selected.

$('#el').datepicker({ 
   onClose: function () {
     // code here
   }
});

Datepicker options https://api.jqueryui.com/datepicker/

苏别ゝ 2024-11-24 05:00:57

这种方法很简单,并且每次都可以与文本框控件一起使用。 $('#controlID').on('changeDate', function() { $(this).change(); });

This approach is simple and works everytime with textbox control. $('#controlID').on('changeDate', function() { $(this).change(); });

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文