Search code examples
javascriptjquerycomparison

JavaScript compare current value with new value


I have a date picker, Kendo to be specific, the value is just a text string value.

I have an on change event firing and I want to compare the current value with the new selected value and then run it some extra code from there. Pretty easy but form some reason I can't figure it out.

I can compare the initial value on document load but on change I need to know on every on change to compare the selected and the current value.

The values coming back in the console for the 'currentDateVal' on every change is the initial value on page load. But on change if someone is running through selecting dates over and over again the 'currentDateVal' is staying the same as the initial page load not the previously selected on a new selection each time.

Here is my code:

$(document).ready(function () {
    var currentDateVal = $("#datepicker").val();
    console.log("initial date: " + currentDateVal);
    //Fill in initial Event Names
    $("#datepicker").on("change", function () {
        var selectedDateVal = $("#datepicker").val();
        //selectedDateVal = currentDateVal;
        console.log("on change current date val: " + currentDateVal);
        console.log("selected date val: " + selectedDateVal);
        if (currentDateVal !== selectedDateVal) {
            console.log("date changed");
        } else {
            console.log("date stayed the same");
        }
 });
});

Solution

  • You never re-set currentDateVal:

    $(document).ready(function () {
        var currentDateVal = $("#datepicker").val();
        console.log("initial date: " + currentDateVal);
        //Fill in initial Event Names
        $("#datepicker").on("change", function () {
            var selectedDateVal = $("#datepicker").val();
            //selectedDateVal = currentDateVal;
            console.log("on change current date val: " + currentDateVal);
            console.log("selected date val: " + selectedDateVal);
            if (currentDateVal !== selectedDateVal) {
                console.log("date changed");
            } else {
                console.log("date stayed the same");
            }
    
            currentDateVal = selectedDateVal;
     });