I'm trying to write a jQuery plugin for displaying and entering dates, using jQuery UI's datepicker as a starting point.
Invoking it should look like this:
jQuery(document).ready(function() {
jQuery(document).find('input.mydatepicker').mydatepicker({
myformat : 'mm/dd/yy'
});
});
such that any input having class="mydatepicker" will have the mydatepicker behavior.
The catch is that I'd like myformat
to support a variety of different date formats, however, whenever I use the val()
function to get/set the date, I want it to be in iso8601 format yyyy-mm-dd
.
So, even though I specified format mm/dd/yy
above to initialize all the elements, I want:
<input type="text" class="mydatepicker" id="myelement" value="02/23/2019">
var mydate = $('#myelement').val(); //mydate = '2019-02-23'
and
$('#myelement').val('2019-02-24');
<input type="text" class="mydatepicker" id="myelement" value="02/24/2019">
Using techniques described here: Override jQuery .val() function? this is what I've tried:
(function($) {
// options & defaults
var defaultOptions = {
myformat : 'mm/dd/yy'
};
// attach jQuery.UI datepicker with specified options
$.fn.mydatepicker = function(options) {
options = $.extend({}, defaultOptions, options || {});
return this.each( function() {
var jq = $(this);
jq.addClass('plugin-mydatepicker').datepicker({
dateFormat: options.myformat,
prevText: '<i class="fa fa-angle-left"></i>',
nextText: '<i class="fa fa-angle-right"></i>',
constrainInput: true,
onSelect: function(date) {
}
});
});
}
// override val() to get/set in ISO8601 regardless of format
var _origVal = $.fn.val;
$.fn.val = function(value) {
if ( $(this).hasClass('plugin-mydatepicker') ) {
if (arguments.length >= 1) {
// setter
return $(this).val('x' + value);
}
else {
// getter
return 'x' + $(this).val();
}
}
return _origVal.apply(this, arguments);
};
})(jQuery);
A couple of things going on here:
- I'm getting "deep recursion" error whenever I call val() and I don't really no why. I'm inexperienced in writing jQuery plugins.
- I haven't done the myformat<->iso8601 conversion yet, open to suggestions on how to do that easily. Practically speaking,
myformat
could be limited to mm/dd/yy and dd/mm/yy, don't need to go crazy there. - To tag each element having the plugin attached, I add a class
plugin-mydatepicker
. Not sure if this is the best way. - I've seen some folks use the
altFormat
option in datepicker. Not interested in this approach if I can avoid it, as it requires creating a second hidden input field, and synchronization between the two. - I'm a bit nervous about overriding the
val()
function; I'd also be open to an alternative get/set function within the plugin, such asmydateVal()
- I'm very open to using some other plugin that does this, that already exists! Just haven't found one myself...
Help?