BviLLe_Kid BviLLe_Kid - 2 months ago 7
jQuery Question

jQuery Change event not firing at all

In my Edit view I have a textbox that accepts

Date
's.

Using MVC, when I go to the Edit View, the fields are already filled in with that record's information which is fine.

But, I want to set an event listener on one of the fields, specifically the field that accepts dates as stated above.

When i go to the page, I check the source and it looks like this for that field:

<div class="form-group">
<label class="control-label col-md-2" for="DateEntered">Date Entered:</label>
<div style="width:26.5%" class="col-md-10">
<div id="datetimepicker" class="input-group date">
<input class="form-control text-box single-line" id="DateEnteredPhase" name="DateEntered" type="datetime" value="09/21/2016" />
<span class="field-validation-valid text-danger" data-valmsg-for="DateEntered" data-valmsg-replace="true"></span>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>


Notice how the value is
"09/21/2016"
which is correct at first.

Here is my jQuery:

$(document).ready(function () {
$(function () {
$('#DateEnteredPhase').change(function () {
var dateString = $('#DateEnteredPhase').val();
alert(dateString);
});
});
});


Now, I have changed the date value in that textbox to
"09/22/2016"
, and the change event is not firing. Also when I check the source after I change the date, the value still says
"09/21/2016"
and not
"09/22/2016"
.

When I plug this into a JSFiddle, the change event is firing appropriately.

How do I fix this?

Any help is appreciated.

UPDATE

Where the DateTimePicker (by eonasdan) is initialized in jQuery:

$(function () {
$('#datetimepicker').datetimepicker({
format: 'MM/DD/YYYY'
});
});

Answer

Problem : Is after you apply the plugin the user has to just change the date via the calendar displayed on the UI, And the plugin will programatically change the date, This will not trigger your change event.

Solution : use the plugin built in event handler to catch the change event and then execute your code. So the below code must work. Here is the change event details from Plugin Documentation

$(function () {
    $('#datetimepicker').datetimepicker({
        format: 'MM/DD/YYYY'
    });

   //add change event listner that plugin supports
   $('#datetimepicker').on('dp.change',function(e){
     alert(e.date);
   })

});