jQuery Datepicker onchange event issue

JqueryDatepickerJquery Ui-Datepicker

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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 input for 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>

Solution 2 - Jquery

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

Solution 3 - Jquery

Your looking for the onSelect event in the datepicker object:

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

Solution 4 - Jquery

$('#inputfield').change(function() { 
	dosomething();
});

Solution 5 - Jquery

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

Solution 6 - Jquery

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

https://stackoverflow.com/questions/22507671/bootstrap-datepicker-change-date-event-doesnt-fire-up-when-manually-editing-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.

Solution 7 - Jquery

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

Solution 8 - Jquery

Try :

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

Solution 9 - Jquery

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 :)

Solution 10 - Jquery

Try this

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

Hope this helps:)

Solution 11 - Jquery

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.

Solution 12 - Jquery

My solution is:

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

Solution 13 - Jquery

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

Solution 14 - Jquery

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

Solution 15 - Jquery

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

Solution 16 - Jquery

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

Solution 17 - Jquery

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

Solution 18 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzbestzeusView Question on Stackoverflow
Solution 1 - JqueryT.J. CrowderView Answer on Stackoverflow
Solution 2 - JquerytheChrisKentView Answer on Stackoverflow
Solution 3 - JquerylocrizakView Answer on Stackoverflow
Solution 4 - Jqueryuser583576View Answer on Stackoverflow
Solution 5 - JqueryCodeDreamer68View Answer on Stackoverflow
Solution 6 - JqueryNMathurView Answer on Stackoverflow
Solution 7 - Jquerytstrand66View Answer on Stackoverflow
Solution 8 - JqueryGiorgosBarkosView Answer on Stackoverflow
Solution 9 - JqueryAlex KoganView Answer on Stackoverflow
Solution 10 - Jquerymike trackerView Answer on Stackoverflow
Solution 11 - JquerySamView Answer on Stackoverflow
Solution 12 - JqueryDaniel OrtegónView Answer on Stackoverflow
Solution 13 - JqueryAndriy PetrushaView Answer on Stackoverflow
Solution 14 - JqueryJeremyView Answer on Stackoverflow
Solution 15 - JqueryHemang RamiView Answer on Stackoverflow
Solution 16 - JquerymavirrocoView Answer on Stackoverflow
Solution 17 - JqueryAndrewView Answer on Stackoverflow
Solution 18 - Jquerygene b.View Answer on Stackoverflow