Unmask datetime - inputmask - javascript

Using Inputmask vanilla js version.
Having problems with unmasking datetime format:
var expDate = document.getElementById('expDate');
Inputmask({
alias: 'datetime',
inputFormat: 'mm/yy',
placeholder: 'month/year',
autoUnmask: true,
clearMaskOnLostFocus: false
}).mask(expDate);
autoUnmask not working, expDate.value returns 12/12, though it should be returning 1212.

I have created a minimal example and the autoUnmask option is working, maybe there are some conflicts with alias: 'datetime' or inputFormat: 'mm/yy'. Read next documentation that is available on the plugin web site:
aliases
With an alias you can define a complex mask definition and call it by using an alias name. So this is mainly to simplify the use of your masks. Some aliases found in the extensions are: email, currency, decimal, integer, date, datetime, dd/mm/yyyy, etc.
First you have to create an alias definition. The alias definition can contain options for the mask, custom definitions, the mask to use etc.
When you pass in an alias, the alias is first resolved and then the other options are applied. So you can call an alias and pass another mask to be applied over the alias. This also means that you can write aliases which "inherit" from another alias.
Some examples can be found in jquery.inputmask.xxx.extensions.js
format
Instead of masking an input element it is also possible to use the inputmask for formatting given values. Think of formatting values to show in jqGrid or on other elements then inputs.
var formattedDate = Inputmask.format("2331973", { alias: "datetime", inputFormat: "dd/mm/yyyy"});
Like you can see, datetime is a defined alias (you can check the definition on inputmask.date.extensions.js), and inputFormat is used for other purposes. On the next example, there is one input with autoUnmask option configured on true and the other with the default value of false:
// Get the inputs fields
var expDate1 = document.getElementById('expDate1');
var expDate2 = document.getElementById('expDate2');
// Apply masks on the inputs.
Inputmask({
alias: 'date',
autoUnmask: true,
clearMaskOnLostFocus: false
}).mask(expDate1);
Inputmask({
alias: 'date',
clearMaskOnLostFocus: false
}).mask(expDate2);
// Alert values.
function getValuesFromInputs()
{
var msg = "Value of Input1 with autoUnmask=true: " + expDate1.value;
msg += "\n"
msg += "Value of Input2 with autoUnmask=false: " + expDate2.value;
alert(msg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/dependencyLibs/inputmask.dependencyLib.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/inputmask/inputmask.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/inputmask/inputmask.extensions.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/inputmask/inputmask.date.extensions.js"></script>
<input type="input" id="expDate1"/>
<input type="input" id="expDate2"/>
<button type="button" onclick="getValuesFromInputs()">Get Values</button>

outputFormat: ddmm does what i needed, but it's not mentioned in documentation of this plugin.

Related

How to change the display format on a P13nItem TimePicker/DatePicker?

I'm trying to change the display format on the DatePicker/TimePicker used by the sap.m.P13nItem when the selected column type is date/time.
I have tried changing the aggregation P13nItem from the P13nFilterPanel in order to include the property formatSettings, but it didn't work.
Here is a sample of my XML view code.
<P13nFilterPanel id="filterPanel" visible="true" type="filter" containerQuery="true" items="{
path: 'SchedulingFilter>/ColumnCollectionFilter'
}" filterItems="{
path: 'SchedulingFilter>/FilterItems'
}">
<P13nItem columnKey="{SchedulingFilter>columnKey}" text="{SchedulingFilter>label}" type="{SchedulingFilter>type}" maxLength="{SchedulingFilter>maxLength}" formatSettings="{SchedulingFilter>formatSettings>" />
<filterItems>
<P13nFilterItem columnKey="{SchedulingFilter>keyField}" operation="{SchedulingFilter>operation}" value1="{SchedulingFilter>value1}" value2="{SchedulingFilter>value2}" exclude="{SchedulingFilter>exclude}" />
</filterItems>
</P13nFilterPanel>
Here is an extract of how I'm filling the bound data.
$.each(columnsKeys, function (i, item) {
const columnData = {};
const columnDescriptionItem = columnDescription[item];
columnData.columnKey = item;
columnData.text = columnDescriptionItem.label;
columnData.type = columnDescriptionItem.type;
columnData.formatSettings = {
pattern: 'yyyy/MM/dd',
UTC: false
};
columnData.maxLength = columnDescriptionItem.maxLength;
columnData.visible = columnDescriptionItem.visible;
columnData.index = columnDescriptionItem.index;
columnData.isEditable = columnDescriptionItem.isEditable;
columnData.isFilter = columnDescriptionItem.isFilter;
columnData.isSorter = columnDescriptionItem.isSorter;
columnsData.push(columnData);
});
The default behavior of the control displays the time/date fields as:
https://ibb.co/JcJJZhJ.
Edit: I discovered that the default behavior is based on the user's locale. I'm not considering the user's locale to change the display format on the others parts of my application.
I want to achieve, for example, the display formats "yyyy/MM/dd" and "hh:mm:ss" on these fields.
I had to extend the P13nConditionPanel (this one is responsible for the time/date components instantiation) and the P13nFilterPanel (it creates the P13nConditionPanel) on version 1.44.6 of SAPUI5 in order to solve this problem. I only had to add the necessary parameters to the DatePicker and TimePicker constructors (as shown below).
case "date":
oConditionGrid.oFormatter = sap.ui.core.format.DateFormat.getDateInstance();
params.displayFormat = DateFormatter.displayFormat();
oControl = new sap.m.DatePicker(params);
break;
case "time":
oConditionGrid.oFormatter = sap.ui.core.format.DateFormat.getTimeInstance();
params.displayFormat = TimeFormatter.getDisplayFormat();
oControl = new sap.m.TimePicker(params);
I posted my customized extended components code on pastebin:
Customized P13nConditionPanel
Customized P13nFilterPanel
I will later open an enhancement request on openui5 Github.

Formly input field validation

I am having an issue with validation messages appearing in an application. Here is the application demo:
https://jsfiddle.net/MrPolywhirl/yxrh3ujp/
I have tried adding validation configuration. This is straight out of the docs.
app.run(function(formlyValidationMessages) {
formlyValidationMessages.messages.required = 'to.label + " is required"';
formlyValidationMessages.messages.max = '"The max value allowed is " + to.max';
formlyValidationMessages.messages.min = '"The min value allowed is " + to.min';
formlyValidationMessages.addTemplateOptionValueMessage('pattern', 'patternValidationMessage', '', '', 'Invalid Input');
});
I have set min/max values on my field. The field does get validated correctly, but the message still does not appear.
Neither the pattern/patternValidationMessage nor the validation (config) function are working for the field. They do nothing and even with a valid pattern, the field still shows that it is invalid (highlighted red).
{
key: 'cooldown',
type: 'input',
templateOptions: {
type: 'number',
label: 'Cooldown (in seconds)',
min : 0,
max : 600,
required: true,
//pattern: /^[0-9]+$/,
//patternValidationMessage: '"Needs to match " + options.templateOptions.pattern'
},
defaultValue: 30,
//validation: {
// messages: {
// required: function ($viewValue, $modelValue, scope) {
// return scope.to.label + ' is required';
// }
// }
//},
}
Can I get some pointers as to why the message will not appear?
Carefully look at the way how formcontrol condition should be setup in error template( specially in ng-if part).
<script type="text/ng-template" id="error-messages.html">
<formly-transclude></formly-transclude>
<div ng-messages="fc.$error" ng-if="options.formControl.$invalid && options.formControl.$touched" class="error-messages">
<div ng-message="{{ ::name }}" ng-repeat="(name, message) in ::options.validation.messages" class="message">{{ message(fc.$viewValue, fc.$modelValue, this)}}</div>
</div>
</script>
Also the way you have written setWrapper method in app config looks messy, so I have removed the code to a separate template and pointed the template here.
Take a look at updated jsfiddle .

Group results in autocompleted dropdown [Meteor]

I try to do a dropdown list in my app. First of all I use a Meteor, so that's specific kind of app ofc :)
Second thing is that I use sebdah/meteor-autocompletion package, because I want my results to be sorted in specific way and limited.
The last thing I need is to group my results.
For example: If I have 2 products named "blah" I want to get only 1 "blag" in my dropdown "autocompletion" list.
Some code:
HTML:
<template name="InvoicesEditInsertInsertForm">
<input id="descriptionautocomplete" type="text" name="description" value="" class="form-control" autofocus="autofocus" placeholder="New Item...">
</template>
JS:
Template.InvoicesEditInsertInsertForm.rendered = function() {
AutoCompletion.init("input#descriptionautocomplete");
};
Template.InvoicesEditInsertInsertForm.events({
'keyup input#descriptionautocomplete': function () {
AutoCompletion.autocomplete({
element: 'input#descriptionautocomplete', // DOM identifier for the element
collection: InvoicesItem, // MeteorJS collection object
field: 'description', // Document field name to search for
limit: 5, // Max number of elements to show
sort: { modifiedAt: -1 },
}); // Sort object to filter results with
},
});
I need to use function that could group my "description" here.
I tried to do it in helper and I get it on my screen, but to be honest I don't know how to put that into my dropdown :(
try: function() {
var item= InvoicesItem.find({},{sort:{modifiedAt:-1}}).fetch();
var descriptions={};
_.each(item,function(row){
var description = row.description;
if(descriptions[description]==null)
descriptions[description]={description:description};
});
return _.values(descriptions);
},
I don't think you can do what you want with that package. If you have a look at the current limitations of the package documentation, you can see other potential solutions to your problem.
You can do addtional filtering as follows:
filter: { 'gender': 'female' }});
but I don't think this will allow you to demand only unique options.
The code you wrote above for try won't do anything. Autocomplete doesn't take a field called try.

Remove Quotes from json_encoded string value

I am working on a project to implement jTable into a PHP framwework class.
It is going quite well. Now I am stuck at a problem where I would like to be able to make custom input fieds on the edit dialog.
We are already using the select2 plugin, now I want to implement this on the edit dialogs of jTable. As far as I understood it is possible to add custom fields to the edit dialog like this:
Name: {
title: 'Name',
width: '20%',
input: function (data) {
if (data.record) {
return '<input type="text" name="Name" style="width:200px" value="' + data.record.Name + '" />';
} else {
return '<input type="text" name="Name" style="width:200px" value="enter your name here" />';
}
}
}
Notice the code above is in JavaScript.
Basically what I do is that I build this javascript in php array and via json_encode I send it to the client.
My problem here is that when I do
$column_array['name']['input'] = function (data) {if ....and so on}
I get on the javascript side
input: "function (data) {... so on"
Please notice the double quotes, it is a string and not a function anymore.
What I would need is to remove this 2 double quotes after the input. (well that's my idea so far)
OR if any one got some experience with jTable] and knows a better way to implement custom fields like select2, chosen, jQuery multiselect, elfinder and stuff like that.
I can give tomorrow some code if needed, cause I am not at work anymore today.
Based on this concept:
// Create a function that takes two arguments and returns the sum of those arguments
var fun = new Function("a", "b", "return a + b");
// Call the function
fun(2, 6);
Output: 8
you may change your JSON a bit in to
Name: {
title: 'Name',
width: '20%',
input: { name: "input",
param: "data",
body: "if (data.record) {
return '<input type=\".... "
}
....
then you may define a function and execute it
var d = new Function(Name.input.name, Name.input.param, Name.input.body);
d(otherdata);
this will omit the awful eval(...) stuff. Caveat: it's still not a method of the given object.

How can I remove AutoNumeric formatting before submitting form?

I'm using the jQuery plugin AutoNumeric but when I submit a form, I can't remove the formatting on the fields before POST.
I tried to use $('input').autonumeric('destroy') (and other methods) but it leaves the formatting on the text fields.
How can I POST the unformatted data to the server? How can I remove the formatting? Is there an attribute for it in the initial config, or somewhere else?
I don't want to send the serialized form data to the server (with AJAX). I want to submit the form with the unformatted data like a normal HTML action.
I wrote a better, somewhat more general hack for this in jQuery
$('form').submit(function(){
var form = $(this);
$('input').each(function(i){
var self = $(this);
try{
var v = self.autoNumeric('get');
self.autoNumeric('destroy');
self.val(v);
}catch(err){
console.log("Not an autonumeric field: " + self.attr("name"));
}
});
return true;
});
This code cleans form w/ error handling on not autoNumeric values.
With newer versions you can use the option:
unformatOnSubmit: true
Inside data callback you must call getString method like below:
$("#form").autosave({
callbacks: {
data: function (options, $inputs, formData) {
return $("#form").autoNumeric("getString");
},
trigger: {
method: "interval",
options: {
interval: 300000
}
},
save: {
method: "ajax",
options: {
type: "POST",
url: '/Action',
success: function (data) {
}
}
}
}
});
Use the get method.
'get' | returns un-formatted object via ".val()" or
".text()" | $(selector).autoNumeric('get');
<script type="text/javascript">
function clean(form) {
form["my_field"].value = "15";
}
</script>
<form method="post" action="submit.php" onsubmit="clean(this)">
<input type="text" name="my_field">
</form>
This will always submit "15". Now get creative :)
Mirrored raw value:
<form method="post" action="submit.php">
<input type="text" name="my_field_formatted" id="my_field_formatted">
<input type="hidden" name="my_field" id="my_field_raw">
</form>
<script type="text/javascript">
$("#my_field_formatted").change(function () {
$("#my_field").val($("#my_field_formatted").autoNumeric("get"));
});
</script>
The in submit.php ignore the value for my_field_formatted and use my_field instead.
You can always use php str_replace function
str_repalce(',','',$stringYouWantToFix);
it will remove all commas. you can cast the value to integer if necessary.
$("input.classname").autoNumeric('init',{your_options});
$('form').submit(function(){
var form=$(this);
$('form').find('input.classname').each(function(){
var self=$(this);
var v = self.autoNumeric('get');
// self.autoNumeric('destroy');
self.val(v);
});
});
classname is your input class that will init as autoNumeric
Sorry for bad English ^_^
There is another solution for integration which doesn't interfere with your client-side validation nor causes the flash of unformatted text before submission:
var input = $(selector);
var proxy = document.createElement('input');
proxy.type = 'text';
input.parent().prepend(proxy);
proxy = $(proxy);
proxy.autoNumeric('init', options);
proxy.autoNumeric('set', input.val())''
proxy.change(function () {
input.val(proxy.autoNumeric('get'));
});
You could use the getArray method (http://www.decorplanit.com/plugin/#getArrayAnchor).
$.post("myScript.php", $('#mainFormData').autoNumeric('getArray'));
I came up with this, seems like the cleanest way.
I know it's a pretty old thread but it's the first Google match, so i'll leave it here for future
$('form').on('submit', function(){
$('.curr').each(function(){
$(this).autoNumeric('update', {aSign: '', aDec: '.', aSep: ''});;
});
});
Solution for AJAX Use Case
I believe this is better answer among all of those mentioned above, as the person who wrote the question is doing AJAX. So
kindly upvote it, so that people find it easily. For non-ajax form submission, answer given by #jpaoletti is the right one.
// Get a reference to any one of the AutoNumeric element on the form to be submitted
var element = AutoNumeric.getAutoNumericElement('#modifyQuantity');
// Unformat ALL elements belonging to the form that includes above element
// Note: Do not perform following in AJAX beforeSend event, it will not work
element.formUnformat();
$.ajax({
url: "<url>",
data : {
ids : ids,
orderType : $('#modifyOrderType').val(),
// Directly use val() for all AutoNumeric fields (they will be unformatted now)
quantity : $('#modifyQuantity').val(),
price : $('#modifyPrice').val(),
triggerPrice : $('#modifyTriggerPrice').val()
}
})
.always(function( ) {
// When AJAX is finished, re-apply formatting
element.formReformat();
});
autoNumeric("getArray") no longer works.
unformatOnSubmit: true does not seem to work when form is submitted with Ajax using serializeArray().
Instead use formArrayFormatted to get the equivalent serialised data of form.serializeArray()
Just get any AutoNumeric initialised element from the form and call the method. It will serialise the entire form including non-autonumeric inputs.
$.ajax({
type: "POST",
url: url,
data: AutoNumeric.getAutoNumericElement("#anyElement").formArrayFormatted(),
)};

Categories