简体   繁体   中英

How do I change programmatically the date of an Anytime datepicker?

I've revised all the Anytime datepicker Q/A on Stackoverflow to no avail. How do I change, not at initialization phase , the date of the picker?

Use Case: I want sometimes the user to pick a date but also sometimes an external event to trigger and update of the picker's current value.

Do you want to update the picker's value (in other words, which buttons are highlighted), or the form field's value? If the latter, then you can just set the field to a new value using typical JavaScript commands. The next time the user clicks the field, the picker will be set according to the value.

The only caveat is that the value you set must be in the same format that you specified for the picker. If you use JavaScript Date objects, then you can convert it to the correct format using a new AnyTime.Converter() initialized with the same format string, and invoke the converter's format() method to convert your Date into a string.

For example:

var FMT = "%e-%b-%Y";
var conv = new AnyTime.Converter({format:FMT});
$("#field").AnyTime_picker({format:FMT});
...
var newVal = new Date(...);
$('#field').val( conv.format(newVal) );

If you're not using a Date object, just be 100% certain that you're formatting the string correctly!

Now, suppose you actually want to change what the picker is showing (for example, you have a picker with placement:'inline' and you want the picker to reflect the new value in the field):

In that case, you'll have to move one line of code in anytime.js, and add one more line of code to your JavaScript:

Firstly, around line 84 of anytime.js, you should find:

var __pickers = [];

A few lines higher, you should find:

(function($)

Move that second line to just above the first one, so you end up with:

var __pickers = [];
(function($)

Then, in your own code, after you set the form field to the new value, call __pickers[ id ].showPkr() for the ID of your form field. For example, continuing my earliest example, add the following last line:

__pickers['field'].showPkr();

Of course, now that you've exposed __pickers[] as a global variable, be sure that you're not using that same name for some other purpose elsewhere, or the names will conflict.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM