set datepicker kendo ui, java script - javascript

I try to set 2 datepickers with a click event.
my code looks like this
$('#previous3Days').click(function () {
var a = $('#MonthBis').data('kendoDatePicker').value();
var d = $('#MonthVon').data('kendoDatePicker').value();
d.setDate(d.getDate() - 3);
$('#MonthVon').data('kendoDatePicker').value(d);
$('#MonthBis').data('kendoDatePicker').value(a);
if (a !== d) {
$('#MonthBis').data('kendoDatePicker').value(a);
a.setDate(a.getDate() - 3);
}
});
my problem is that the KendoComboBox don't change the value of the "Monthbis".
i tried every possibility like if (a>d) or (a!=d).
If i use (a>=d) every click both dates get changed.
i also checked the console in my browser according to this both dates are always the same and i don't see my fault.

I think that the problem is in the logic of your program...
Changing MonthVon is ok since you (in order) you wrote:
var d = $('#MonthVon').data('kendoDatePicker').value(); // Line 4
d.setDate(d.getDate() - 3); // Line 5
$('#MonthVon').data('kendoDatePicker').value(d); // Line 7
But for MonthBis the logic is pretty odd... This is what you wrote:
var a = $('#MonthBis').data('kendoDatePicker').value(); // Line 3
$('#MonthBis').data('kendoDatePicker').value(a); // Line 8
So you did nothing so far since you read and write the same value.
Then you check that a !== c and if so you do:
$('#MonthBis').data('kendoDatePicker').value(a); // Line 10
a.setDate(a.getDate() - 3); // Line 11
You modify a but you do nothing with it's value so it actually does nothing.
Probably, you should swap lines 10 and 11 so you would have:
$('#previous3Days').click(function () {
var d = $('#MonthVon').data('kendoDatePicker').value();
d.setDate(d.getDate() - 3);
$('#MonthVon').data('kendoDatePicker').value(d);
var a = $('#MonthBis').data('kendoDatePicker').value();
if (a !== d) {
a.setDate(a.getDate() - 3);
$('#MonthBis').data('kendoDatePicker').value(a);
}
});

Related

Check if time range overlaps with another time range

Assume i have a start date and a end data as follows
end: "2021-10-22T06:00:00.000Z"
start: "2021-10-22T05:00:00.000Z"
I want to check if another given time range overlaps with the above time range in javascript. I tried using moment as follows.
return (
moment(timerange1.duration.end) <= moment(timerange2.duration.start) ||
moment(timerange1.duration.start) >= moment(timerange2.duration?.end)
);
But this does not produce the correct results. What would be the correct way to check if a certain time range overlaps with another time range using javascript?
Consider this:
In case A and C they do not overlap.
But what is true in B that isn't true in A or C?
Well, the start, or the end of the red one, is between the start and end of the blue one. That will always be true for overlapping timeperiods.
Example code:
if( (red.start > blue.start && red.start < blue.end) || (red.end > blue.start && red.end< blue.end) ) {
// do something
}
return (
(moment(timerange1.duration.start) >= moment(timerange2.duration.start) && moment(timerange1.duration.start) <= moment(timerange2.duration.end))
|| (moment(timerange1.duration.end) >= moment(timerange2.duration.start) && moment(timerange1.duration.end) <= moment(timerange2.duration.end))
|| (moment(timerange2.duration.start) >= moment(timerange1.duration.start) && moment(timerange2.duration.start) <= moment(timerange1.duration.end))
)
there are 3 different cases to consider as overlap
timerange1: |-----|
timerange2:     |-----|
timerange1:     |-----|
timerange2: |-----|
timerange1: |-----------|
timerange2:     |-----|
You can use the twix.js plugin for moment to handle the date ranges. In your code, you need to do something like that. This is sample code snippet you can modify it according to your need.
var t1 = {
start: "1982-01-25T09:30",
end: "1982-01-25T13:30",
};
var t2 = {
start: "1982-01-23T13:30",
end: "1982-01-25T12:30",
};
var t3 = {
start: "1982-01-24T13:30",
end: "1982-01-25T10:30",
};
var t1Range = moment(t1.start).twix(t1.end);
var t2Range = moment(t2.start).twix(t2.end);
var t3Range = moment(t3.start).twix(t3.end);
t1Range.overlaps(t2Range) || t1Range.overlaps(t3Range); //=> true

Collection Boolean isn't being set to false - Meteor

So in short, the app that i'm developing is a bus timetable app using Meteor, as a practice project.
inside my body.js, I have an interval that runs every second, to fetch the current time and compare to items in a collection.
To show relevant times, I have added an isActive boolean, whenever the current time = sartTime of the collection, it sets it to true, and that is working fine.
But when I do the same thing for endTime and try to set it to false, so I can hide that timeslot, it just doesn't work. Even consoles don't show up. What am I missing? I have recently just started doing meteor, so excuse the redundancies.
Worth noting that the times that I'm comparing to are times imported from an CSV file, so they have to be in the 00:00 AM/PM format.
Thank you guys so much for your time.
Body.js code:
Template.Body.onCreated(function appBodyOnCreated() {
Meteor.setInterval(() => {
var h = (new Date()).getHours();
const m = ((new Date()).getMinutes() <10?'0':'') + ((new Date()).getMinutes());
var ampm = h >= 12 ? ' PM' : ' AM';
ampmReac.set(ampm);
if (h > 12) {
h -= 12;
} else if (h === 0) {
h = 12;
}
const timeAsAString = `${h}${m}`;
const timeAsAStringFormat = `${h}:${m}`;
whatTimeIsItString.set(timeAsAStringFormat + ampm); // convert to a string
const timeAsANumber = parseInt(timeAsAString); // convert to a number
whatTimeIsIt.set(timeAsANumber); // update our reactive variable
if (Timetables.findOne({TimeStart: whatTimeIsItString.get()}).TimeStart == whatTimeIsItString.get())
{
var nowTimetable = Timetables.findOne({TimeStart: whatTimeIsItString.get() });
Timetables.update({_id : nowTimetable._id },{$set:{isActive : true}});
console.log('I am inside the START statement');
}
else if (Timetables.findOne({TimeEnd: whatTimeIsItString.get()}).TimeEnd == whatTimeIsItString.get())
{
var nowTimetable = Timetables.findOne({TimeEnd: whatTimeIsItString.get() });
Timetables.update({_id : nowTimetable._id },{$set:{isActive : false}});
console.log('I am inside the END statement');
}
}, 1000); //reactivate this function every second
});
})
Very probably it is just that your if / else blocks does what you ask it:
It tries to find a document in Timetables, with specified TimeStart. If so, it makes this document as "active".
If no document is previously found, i.e. there is no timeslot which TimeStart is equal to current time, then it tries to find a document with specified TimeEnd.
But your else if block is executed only if the previous if block does not find anything.
Therefore if you have a next timeslot which starts when your current timeslot ends, your if block gets executed for that next timeslot, but the else if block is never executed to de-activate your current timeslot.
An easy solution would be to transform your else if block in an independent if block, so that it is tested whether the previous one (i.e. TimeStart) finds something or not.
Ok so I got it to work eventually. My problem was that it was never going to the second IF statement.
What I have done is set up a whole new Meteor.interval(() >) function, and placed that second IF in there, as is.
I think the problem was that it was it checks the first IF statement and gets stuck there, no matter what the outcome of the parameters is.

number incrementing in Angular.js

I'm attempting to build an app that calculates sales metrics. I have run into an unusual problem in my build.
Part of the app allows users to increase/decrease a variable by 5% and then see how that will effect an overall metric. It also allows the user to see the percentage increase/decrease.
I have the functionality working roughly as intended, however if I enter a number lower than 20 into the input and then try in increase it with my incrementing function it only increments once and then stops.
If the number I enter into the input is 20 or greater it increments in the intended way.
Below is my angular code:
function controller ($scope) {
$scope.firstNumber = 0;
$scope.firstPercent = 0;
$scope.increase = function(id) {
var A = parseInt(id);
var B = A * 5/100;
var C = 0;
var C = A + B;
if (id === $scope.firstNumber) {
$scope.firstNumber = C;
$scope.firstPercent = $scope.firstPercent + 5;
}
};
$scope.decrease = function(id) {
var A = parseInt(id);
var B = A * 5/100;
var C = 0;
var C = A - B;
if (id === $scope.firstNumber) {
$scope.firstNumber = C;
$scope.firstPercent = $scope.firstPercent - 5;
}
};
I can't see anything wrong with my maths, my thinking is that perhaps I'm approaching angular in the wrong way. However I'm not sure.
I have put together a fiddle that shows the full code.
jsFiddle
I have updated the fiddle to use parseFloat. Seems like the numbers are incrementing now.
var A = parseFloat(id);
http://jsfiddle.net/kjDx7/1/
The reason why it was working with values above 20 was that it was just reading the part before decimals each time it tried to increase. So 20 became 21 and 22.05 and so on. As long the the value before decimal kept changing, it showed different (but incorrect) answers.
On the other hand, 10 became 10.5 which when parsed yielded 10. As you can see, this cycle continued endlessly.
The reason why you face the issue is because 5% of anything less than or equal to 20 is less than or equal to 1.
When you parseInt() the value, you always end up with the same number again.
Take 15 for example.
5% of 15 = 15.75
After parseInt(), you get the value 15 again.
You use the same value to increment / decrement each time.
Hence for values below 20, you don't get any changes.
As #Akash suggests, use parseFloat() instead - or why even do that when the value that you get is float anyway
I made a fork of your fiddle. I'm not completely sure what you want to achive.
Take a look at this fiddle.
$scope.increase = function() {
$scope.firstPercent = $scope.firstPercent + 5;
var A = $scope.firstNumber;
var B = (A / 100) * $scope.firstPercent;
var C = A + B;
$scope.firstNumberWithPercent = C;
};
update
After posting, i see that question is already answered. But is this what you really want? When you hit increase, it takes 5 % off of the number in the input field. That is ok, but when you hit decrease after that, it takes 5 % off the number in the same field. So your starting point is different.
100 + 5/100 = 105
105 - 5/105 = 99,75

Why is this bang in the If Then Failing Here

The value in div PermanentHiddenDiv3 can be -11, 1, 6, 12, 17, 18 or 29.
However, at the point in the script where this code exists, the value should
only ever be 18. So, I could go with that.
On the other hand, if I could get this to work with other values being
handled as well, it would be better.
var OMGxAlgebra = function(evt){
var AltReality = document.getElementById("Latent29");
var AreYouSAVED;
var SingleEval = document.getElementById("PermanentHiddenDiv3");
var ThinkingIsAntiSocial = SingleEval.textContent;
OhItIS = ThinkingIsAntiSocial*1;
// You can write this ::
// if(OhItIS==18){
// AreYouSAVED="";
// AltReality.textContent=AreYouSAVED;
// }
if(OhItIS==18){
AreYouSAVED="";
AltReality.textContent=AreYouSAVED;
}
};
The code above works, but the next does not. I thought that in JavaScript
this syntax was valid ???
if(!somevar==X){}
if(!OhItIS==29){
AreYouSAVED="";
AltReality.textContent=AreYouSAVED;
}
The code in context : http://jsfiddle.net/MountainMan72/4gySs/ ... just in case
I am missing some external tripwire.
Use
if (OhItIS != 29){
AreYouSAVED="";
AltReality.textContent=AreYouSAVED;
}
The bang goes before the =
!=
I'm pretty sure you want to use OhItIS != 29
Using !OhItIS == 29 converts OhItIs to a boolean value and compares that to 29. Obviously ends in results that you don't want.
Try this in your browser for verification:
var ohitis = 29;
console.log(!ohitis);
This should print out false;
The precedence rules mean that !x==y parses as (!x) == y, not !(x == y). As the other answers said, use x != y to avoid the problem.

2 or 4 Digit Date Validation with Javascript String Replacement

EDIT: To anyone making the same mistake I did in asking this question, please look for my amended answer below which demonstrates a MUCH cleaner solution to this problem.
Trying to permit user entry of either 2 digit or 4 digit date format and allow both to pass validation but autocorrect the 2 digit format with the 4 digit equivalent with the assumption that the leading 2 digits should be the same as the current leading 2 digits.
I'm having trouble with the javascript replace() function. This line:
input.replace(enteredDate, year);
is not working as expected. In the context of the spine.js framework I'm using, the input refers to $(event.target) and appears to be correct everywhere else in manipulating the input field where the validation should be occurring. Ultimately, I want to replace the original string found in the input field with the fully concatenated one (which I haven't built out yet), but for now, how can I replace the contents of input (where input is var = $(event.target)) with the var year assigned here:
var year = currentYear.charAt(0) + currentYear.charAt(1) + unparsedYear;
Here is the full code for the function I have so far, which is throwing the following error in reference to the .replace() line - Uncaught TypeError: Object [object Object] has no method 'replace'
validateDate: function(event) {
var input = $(event.target);
var enteredDate = input.val();
input.destroyValidationMessage();
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{2})|(\d{4})$/;
var result = enteredDate.match(pattern);
if (result !== null) {
var month = parseInt(result[1], 10);
var day = parseInt(result[2], 10);
var year = parseInt(result[3], 10);
var unparsedYear = parseInt(result[3], 10);
var unparsedYearStrLength = unparsedYear.toString().length;
if ( unparsedYearStrLength < 4) {
var currentYear = new Date().getFullYear().toString();
var year = currentYear.charAt(0) + currentYear.charAt(1) + unparsedYear;
alert('Autocorrected year will be ' + year);
input.replace(enteredDate, year);
}
var date = new Date(year, month - 1, day);
var isValid = date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
} else {
input.createValidationMessage('Invalid Date');
input.addClass('invalid');
}
}
As mentioned in my comment above:
input is a DOM element, but you actually want to replace the content of the element vs. the element itself, so use input.val(new_value) and not the actual input element.

Categories

Resources