Using dijit.form.DateTextBox Not able to retain proper Time value - javascript

I am using dijit.form.DateTextBox to update my date field.
<form:input id="date_id" name="date_field" path="createDate"
dojoType="dijit.form.DateTextBox"
disabled="false" constraints="{datePattern:'dd/MM/yyyy hh:mm:ss.SS'}"
invalidMessage="invalid" promptMessage="invalid"
lang="en-us" required="true"/>
now, suppose If my 'createDate' value is '05/01/2012 21:10:17.287', but it is displaying as '05/01/2012 12:00:00.00' in date text box.
Due to which, while editing this field, I'm not able to keep it as it was.
Is there anyway I can retain that time part '21:10:17.287'.
Kindly suggest.

(This solution will work for above Dojo 1.6 versions )
The default DateTextBox overrides the old value when setting a new one. This means that the time context is lost while setting the value. If you want to make this possible, you will have to extend the default behavior of the _setValueAttr function of DateTextBox since this is the setter of the value field.
This is how you could do this:
declare("custom.DateTextBox", [DateTextBox], {
_setValueAttr: function(value, priorityChange, formattedValue) {
if(value !== undefined){
if(typeof value == "string"){
value = stamp.fromISOString(value);
}
if(this._isInvalidDate(value)){
value = null;
}
if(value instanceof Date && !(this.dateClassObj instanceof Date)){
value = new this.dateClassObj(value);
}
}
if (value != null && this.value != null) {
value.setHours(this.value.getHours());
value.setMinutes(this.value.getMinutes());
value.setSeconds(this.value.getSeconds());
value.setMilliseconds(this.value.getMilliseconds());
}
this.value = value;
this.inherited(arguments);
}
});
What happens here is pretty easy, the first thing I do is parsing the new value to a valid Date. Before replacing the original value I'm copying the time fields (hours, minutes, seconds and milliseconds).
I also made a JSFiddle to demonstrate this.

Related

Combine model and boolean variable in expressionProperties - Formly

I want to set formly form fields disabled value based on model properties and boolean variable. This doesn't seem to work
expressionProperties: {
'templateOptions.disabled': 'model.advancePayments && !model.deposit' || vm.acquisitionCancelledFlag
}
It works but the || vm.acquisitionCancelledFlag doesn't make any difference
vm.acquisitionCancelledFlag is true but the field isn't disabled
I have also tried
'templateOptions.disabled': '(model.advancePayments && !model.deposit) || vm.acquisitionCancelledFlag'
Spent some time on this but figured out I can do this instead so I'm sharing it with people who might need it. Not the most elegant but works
expressionProperties: {
'templateOptions.disabled': function(viewValue, modelValue, scope) {
return (scope.model.advancePayments && !scope.model.deposit) || vm.acquisitionCancelledFlag;
}
}

how to use $scope.arr.filter in angular js?

I am trying to use filter method in angular with moment js .When I filled these field on my fields an click search button .It show no result .It should show one result .
"TO" : "DEL"
"FROM" :"PNQ"
"DEPART Date" : "10-01-2017"
here is my code
https://plnkr.co/edit/k4FBxqufETslgYxm4zEx?p=preview
$scope.searchClick =function(){
if($scope.fromStation!='' && $scope.toStation!='' && $scope.departDate !=''){
$scope.names = $scope.defaultNames.filter(function(item){
var time1 = moment(item.flight_date, "DD-MM-YYYY");
var time2 = moment($scope.departDate, "DD-MM-YYYY");
console.log(moment(time1).isSame(time2))
return item.to_station === $scope.toStation
&& item.from_station === $scope.fromStation
&& moment(time1).isSame(time2)
})
}
}
This line gives true on first object .but not shown in output why ?
console.log(moment(time1).isSame(time2))
I guess you got it a bit wrong. The $filters in Angular 1 are different from the filter in JavaScript Arrays. The thing you have done above should return an object not True or False as your return statement is doing. You can try modifying it a bit so as to return the values in first place and then the date time issue can be looked into. More over the plunkr you shared does not have the code your have mentioned in the question.
Have a look at this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?v=control It might be helpful

ExtJS ComboBox validation returns unexpected result

I've just been working on a ExtJS script and I have a ComboBox which has
allowBlank = false
and
forceSelection = true
I have an item in the list which acts as a default message which has a display text
Please select...
and no value
''
When I run validate on the ComboBox I get true
No idea why?
According to the documentation when
allowBlank = false
the validation is forced to check for value.length > 0
So I have done my own test in the JS Console
>> if (thisForm.controlManager.controlArray[2].allowBlanks) { if (thisForm.controlManager.controlArray[2].length >= 0) { true; } false; } else { if (thisForm.controlManager.controlArray[2].length > 0) { true; } false; }
and it returned false
So I thought it might a bug in validate method so I tried doing this
>> thisForm.controlManager.controlArray[2].validateValue('')
and got this as a result true
Any one have any kind of idea of what I might be doing wrong or if anything else needs set to get this validate to return false when value is ''.
PS. I've also tried this
>> thisForm.controlManager.controlArray[2].validateValue(' ')
and got the correct result which is false. This made me very confused as I would normally expect '' and ' ' to return the same value in validation.
I know that a workaround would be to set my value to ' ' but I would rather get it working with ''.
Thanks
I just so happened to end up grappling with this same issue, and after some looking around, managed to find a solution which does not require overriding Extjs's standard functionality.
Basically, there is a 'validator' config option for descendents of Ext.form.field.Text which allows programmers to specify a custom validation function for a component (see here).
Basically, your validator function gets called at the start of getErrors() and is evaluated before the rest of the field's standard validation. The validator function takes one argument (the value) and must return either true if the value is valid or an error message string if it is not.
The following config ended up working for my case:
validator: function (value) {
return (value === '/*Your emptytext text*/') ? "blankText" : true;
}
You have to use the emptyText configuration
Ext have this code for validate fields:
validate : function(){
if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
this.clearInvalid();
return true;
}
return false;
}
and getRawValue is defined like this:
getRawValue : function(){
var v = this.rendered ? this.el.getValue() : Ext.value(this.value, '');
if(v === this.emptyText){
v = '';
}
return v;
}
so, if the value is equal to the empty text, the returned value is ''

knockoutjs, observables updating each other

I have view model with 3 fields
dateStart = ko.observable();
dateEnd = ko.observable();
days = ko.observable();
assuming startDate is selected, whenever endDate is selected days field needs to be updated (days = endDate - startDate).
Also when days field is updated i need to calculate endDate (endDate = startDate + days).
how can this be done with knockoutjs ?
Thank You!
I've tried
http://jsfiddle.net/NfG4C/6/, but my js always throws too musch recursion exception.
From what I understand, you basically need 2 things.
You want to calculate the "days" field whenever someone selects the
"endDate" [assuming they have selected the "startDate" ofcourse]
You want to recalculate the "endDate" field whenever someone changes the
"days" field
One way to solve this would be to use a "writeable" computed Observable [http://knockoutjs.com/documentation/computedObservables.html]. Please go through the link for details, but in general term, a 'writeable computed observable' is something whose value is 'computed' based on some 'other' observable(s) and vice-versa.
I took the liberty to modify your fiddle and change the "days" as a computed observable. Please take a look: http://jsfiddle.net/dJQnu/5/
this.days = ko.computed({
read: function () {
//debugger;
// here we simply need to calculate the days as => (days = endDate - startDate)
if (that.dateStart() && that.dateEnd()) {
var vacDayCounter = 0;
for (var curDate = new Date(that.dateStart()); curDate <= that.dateEnd(); curDate = curDate.addDays(1)) {
if (isDateCountsAsVacation(curDate)) {
vacDayCounter++;
}
}
//that.days(vacDayCounter);
return vacDayCounter;
}
},
write: function (newDays) {
if (newDays && !isNaN(newDays) && that.dateStart()) {
var tmpEndDate = new Date(that.dateStart())
appliedDays = 0;
while (appliedDays < newDays) {
if (isDateCountsAsVacation(tmpEndDate)) {
appliedDays++;
}
tmpEndDate = tmpEndDate.addDays(1);
}
if (tmpEndDate) {
that.dateEnd(tmpEndDate);
}
}
}
});
If you notice, I simply reused your code (logic) for the read and write part. During read, we are "computing" the value for the observable itself, in this case the "days" and during write (which fires anytime the user changes the actual "days" input value) we are recalculating the "dateEnd" field.
Please let me know if you have any other question.
Hope this helps.
Thanks.
You get a recusive problem because when updating the observables from a subscription will also trigger that observables subscribe method.
You need to add a fourth member, updatedFromSubscriber
set it to false from tbe beginning, in each subscribe method add
if(this.updatedFromSubscriber)
return;
and just before updating the observable do
this.updatedFromSubscriber = true
set it to false after updating the observable

lack of identity between jQuery selector and jQuery variable?

I'm running into a maddening problem where I set a variable to point to a jQuery selector, such as: var foobar=jQuery(this); I then pass this variable to a function to be worked on. Let's simplify a little and say the function looks like this:
function SetFieldValue (selector) {
selector.val('test');
console.log ( selector );
console.log ( jQuery('#' + selector.attr('id')) );
}
In this situation if you assume that:
the selector is always a form element (and therefore val() is a valid operation)
the selector does resolve to a single dom element which has an 'id' attribute
You would then expect the two console.log statements to output the same result, right? Well I'm running into a situation where this condition only happens about 90% of the time.
In order to give more context I've created a short screencast demonstrating the problem:
SCREENCAST LINK
For reference purposes, here's the actual SetFieldValue code that is shown in the screencast:
function SetFieldValue ( domObject, value ) {
// as a safety function, check if a string representation of the domObject was passed in and convert it to a jQuery object if it was
if ( jQuery.type(domObject) === "string") {
console.log ("Value passed into SetFieldValue was a string representation so converting to jQuery object");
domObject = jQuery(domObject);
}
if ( jQuery.inArray (domObject.prop('tagName').toLowerCase(),['input' , 'select' , 'textarea']) >= 0 ) {
console.log ("setting to value attribute: " + value);
if ( domObject.hasAttr('id') ) {
domObject.val(value);
//jQuery('#' + domObject.attr('id')).val(value);
} else {
domObject.attr('value',value);
}
console.log ("Using jQuery ID it is set to: " + jQuery('#' + domObject.attr('id')).val() );
console.log ("Using jQuery selector variable it is set to: " + domObject.val() );
} else {
console.log ("setting to html attribute");
domObject.html( value );
}
return domObject;
}
Lets examine the code a bit.
First assigning back to a parameter is not a good practice adding a var at the start of your function would be a lot better, as scope can be lost.
//Suggestion change parameter to domItem
var domObject
Your missing an error handler for when the parameter is not String.
when identifying the type use
<VARNAME>.constructor.toString().match(/function (\w*)/)[1] === "<TYPE>"
It's more efficient and handles custom types.
No need for all the logic in assignment of value attribute. Any dom Object can be made to have a value attribute. also not sure why you are setting the val versus the value.
domObject.attr('value',value);
It is at this point that I can see your code could really use some documentation to help explain purpose
If you are explicitly only wanting to set value on Input fields and set value as innerhtml on non input fields then yes the logic would be needed but could be simplified to ... as the value doesn't need to be detected to overwritten.
if (jQuery.inArray (domObject.prop('tagName').toLowerCase(), ['input' , 'select' , 'textarea']) >= 0) {
domObject.attr('value',value);
} else {
domObject.html( value );
}
No Idea why you are returning the domObject out.
So a quick rewrite without the return and keeping most of the logic adding error handling results in
/*jslint sloppy: true*/
/*global jQuery*/
function SetFieldValue(domString, value) {
// as a safety function, check if a string representation of the domObjects was passed in and convert it to a jQuery object if it was
var domObjects, index;
//errorhandling
if (domString === undefined || domString === null) {
throw {error : "domString must have a value."};
}
if (domString.constructor.toString().match(/function (\w*)/)[1] !== "string") {
if (domString.constructor.toString().match(/function (\w*)/)[1].match(/HTML[a-zA-Z]*Element/) === null) {
throw {error : "domString expected to be String or domObjects"};
}
} else {
if (jQuery(domString).length === 0) {
throw {error : "domString does not resolve to a detectable domObjects."};
}
}
//errorhandling
//action
if (domString.constructor.toString().match(/function (\w*)/)[1].match(/HTML[a-zA-Z]*Element/)) {
//made as an array to normalize as jQuery returns an array allows code to be simplified
domObjects = [domString];
} else {
domObjects = jQuery(domString);
}
//given that domObjects are an array need to step through the array
for (index = domObjects.length - 1; index >= 0; index -= 1) {
if (
jQuery.inArray(
domObjects[index].tagName.toLowerCase(),
['input', 'select', 'textarea']
) >= 0
) {
if (domObjects[index].hasAttr('id')) {
domObjects[index].val(value);
} else {
domObjects[index].attr('value', value);
}
} else {
domObjects[index].html(value);
}
}
}
The above passes JSLint
I know I didn't provide enough context for people to really dig into this problem but I have in the end solved it. What was the issue? Well it was #Kobi who first asked is the DOM element's ID unique ... to which I happily reported it was. And it had been but in fact that WAS the problem. Jesus. It's always the obvious things that you then go onto overlook that get you in trouble.
Anyway, thanks for your patience and help.

Categories

Resources