Question

I'm using the datetimepicker from http://trentrichardson.com/examples/timepicker/

The problem is that I've got an start and end input field. I don't want that an user can pick an end datetime that is later then the start date field.

The input fields looks like this:

<input type="text" name="dateStart" id="dateStart" value="<?php echo $pageInfo['page_date_start'];?>" onChange="dateStartChange();" />
<input type="text" name="dateEnd" id="dateEnd" value="<?php echo $pageInfo['page_date_end'];?>" onChange="dateEndChange();" />
// Default date value = 0000-00-00 00:00:00

The JScript that setups the datetimepicker:

$('#dateStart').datetimepicker({
    showSecond: false,
    timeFormat: 'HH:mm:ss',
    dateFormat: "yy-mm-dd",
});

$('#dateEnd').datetimepicker({
    showSecond: false,
    timeFormat: 'HH:mm:ss',
    dateFormat: "yy-mm-dd",
});

And the onchange functions:

function dateStartChange(){
    console.log("dateStartChange: " + $("#dateStart").val());
    $("#dateEnd").datepicker('option', 'minDate', $("#dateStart").val()); 
}

function dateEndChange(){
    console.log("dateEndChange: " + $("#dateEnd").val());
    $("#dateStart").datepicker('option', 'maxDate', $("#dateEnd").val()); 
}

This works great except for one thing. If I change the date, and then click on the other input field and SELECT the same day, it results in an infinite loop if I check my console log: Console output...

And the page (chrome) changes to this: Page outcome

Is it a problem with the datetime picker or am I doing something wrong? I don't get it.

Was it helpful?

Solution

It is probably recursion....

When dateStart changes, you are modifying dateEnd.
When dateEnd changes, you are modifying dateStart.
When dateStart changes, you are modifying dateEnd.
When dateEnd changes, you are modifying dateStart.
When dateStart changes, you are modifying dateEnd.
When dateEnd changes, you are modifying dateStart.
When dateStart changes, you are modifying dateEnd.
When dateEnd changes, you are modifying dateStart.

etc., etc., etc.

[Edit suggested work around, apply to both event handlers]

var bCodeChange = false;

function dateStartChange()
{
    if (bCodeChange == true)
        return;
    else
        bCodeChange = true;

    console.log("dateStartChange: " + $("#dateStart").val());
    $("#dateEnd").datepicker('option', 'minDate', $("#dateStart").val());

    bCodeChange = false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top