jQuery UI datepicker: Can you format a date and allow multiple seperator characters?
I prefer my datepicker to be formatted with this option
{dateFormat: 'mm-dd-yy'}
Ex: 06-16-2010
But开发者_如何学Python, I would like to allow people to enter in a slash as a seperator instead of a dash if they choose.
Is there a way to setup the datepicker so that it defaults to mm-dd-yy but wouldn't prevent someone from entering mm/dd/yy?
I do know I can set {constrainInput:false} although then people can enter letters :(
Thanks for any help.
Absolutely. You can type anything into the field if you turn off constrainInput.
$( "#myDateInput" ).datepicker({
dateFormat: 'mm-dd-yy',
constrainInput: false
});
Full docs: http://api.jqueryui.com/datepicker/#option-constrainInput
the datepicker has the altField & altFormat option so you can show one format but send the other, but thats not what you want.
i suggest that you use datejs (http://www.datejs.com/) to parse the user input and update a hidden textbox which is linked to your datepicker.
The constraininput will do the trick. I was trying to do a similar thing, and I bound the change to do a few extra things. You can use any delimiter. / - . , space etc. It converts any non digit to /. If you enter m/d or m/d/ it will add the current year using any delimiter. If you do T or t, it will return the current day. You can do T10 or T+10 and it will return today plus 10 days. You can do t-10 and it will return 10 days prior. You can change the 2 places where it has "mm-dd-y" to use your desired format. This solution should work for international format as except for the auto date add, but I did not test it for that.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$(function() {
$( "#STARTDATE" ).datepicker({
numberOfMonths: 4,
showButtonPanel: true,
constrainInput: false,
dateFormat: "mm-dd-y"
});
$( "#STARTDATE" ).change(function() {
if ($("#STARTDATE").val().toUpperCase().indexOf("T") >= 0) {
Days = parseInt("0" + $("#STARTDATE").val().replace(/\D/g,''));
if ($("#STARTDATE").val().indexOf('-') >= 0){Days*=-1}
var tdate = new Date();
tdate.setDate(tdate.getDate() + Days);
} else {
var tdate = $("#STARTDATE").val().replace(/[^0-9]+/g, '/');
var tvar = tdate.split("/");
if (tvar.length == 3){
if (tvar[2] == "") {tdate += new Date().getFullYear().toString().substr(-2)}
}
if (tvar.length == 2){tdate += "/" + new Date().getFullYear().toString().substr(-2)}
try {
tdate = $.datepicker.parseDate('mm/dd/y', tdate);
} catch (Error) {
try {
tdate = $.datepicker.parseDate('mm/dd/yy', tdate);
} catch (Error) {
}
}
}
tdate = $.datepicker.formatDate( "mm-dd-y", new Date( tdate ) );
$( "#STARTDATE" ).val(tdate);
});
});
</script>
精彩评论