Get start end date customRange datepicker angularjs - javascript

Hi everyone I have a custom range to pick a day in angularjs. I need a listener when i pick two days (start and end) to get the values and autoamtically send this data to my rest api.
View :
<div class="form-group col-md-3 mb0" ng-if="timerange == 'custom'" id="customDiv">
<div class="row">
<label class="col-sm-3 control-label pt7">Custom</label>
<div class="col-sm-9">
<input type="text" id="customrange" name="customrange" ng-model="parent.customrange" ng-change="applyOptions()" class="form-control" ui-jq="daterangepicker" ui-options="{format: 'YYYY/MM/DD',startDate: '{{startdate}}',endDate: '{{enddate}}', maxDate:'{{enddate}}'}" />
</div>
</div>
</div>
When i click in my range dropdownbox i choose custom and then it popups a input with a date picker.. I need when i press apply to get the data.. I read a lot of documentation and cant add a listener to this... I really need to find a way...
Controller:
var rangeSelector = document.getElementsByTagName('select')[1]; //1h 24h 1w custom
if(rangeSelector.value == 'custom'){
getDate = controllerScope.getStartEndTimestamps();
var datePicker = document.getElementById("customrange").getAttribute('ui-options');
var split = datePicker.split(",");
var startDate = "";
var endDate = "";
document.getElemenstByTagName("button")[0].addEventListener("click", function(){
alert("I've changed : ");
startDate = split[1].split(': ')[1].replace(/["']/g, '');
endDate = split[2].split(': ')[1].replace(/["']/g, '');
});
console.log("range selector ",rangeSelector);
console.log("startDate ",startDate);
console.log("endDate ",endDate);
if (startDate !== undefined) {
url += '&startDate='+startDate;
}
if (endDate !== undefined) {
url += '&endDate='+endDate;
}
}
Logs:
range selector ​…​​
startDate
endDate
The problem is the alert "I've changed" dont popup... is there a simple way to do this??

Related

How to filter records from a Datatable from a given range of date for a single column

I have a single date field createdDate in my datatable. and the 2 drop downs which gives starting date and end date. what I want to do is after clicikng on a button the records should get filtered out.
<div class="col-md-6 col-sm-6">
<input type="date" class = "createdDateFilter" id="createdDateFrom" name="createdDateFrom">
</div>
<label class="col-md-3 col-sm-3" for="createdDateTo">Created Date(To)</label>
<div class="col-md-6 col-sm-6">
<input type="date" class = "createdDateFilter" id="createdDateTo" name="createdDateTo">
</div>
<div class="buttons">
<input class="btn btn-primary btn-sm" id="search" type="submit" value="Search">
</div>
My JS file:
// This will update the start date
$("#createdDateFrom").change(function () {
// currentdate.getMonth() + 1) + "/" + currentdate.getDate() + "/" + currentdate.getFullYear();
createdDateFrom = new Date($(this).val());
});
// This will update the end date
$("#createdDateTo").change(function () {
createdDateTo = new Date($(this).val());
});
I am pretty much blank ahead of this. Is it even possible? I am aware of the search input filters for every column but I want a separate button. Thanks!
I just seen this thread on StackOverflow which could help you
Compare two dates with JavaScript
He created a class, that you have to copy one of his function in your code like this :
function inRange(d,start,end) {
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
So according to his anwser, you can use it in filter function.
You'll have to get your datas array in var.
Suppose we have
let arr = [/*your datas*/]
You can simply return the filter result applied on 'arr'
function getOnlyInRangeDateItems(arr, startDate, endDate) {
return arr.filter(item => inRange(item.createdDate, startDate, endDate))
}
Finally, just call it :
let date1 = new Date($("#createdDateFrom").val())
let date2 = new Date($("#createdDateTo").val())
let datasInRange = getOnlyInRangeDateItems(arr, date1, date2)

Datepicker validation not functioning on first try

I am currently working on a site using MEAN. In this site, I am using html5 datepicker but since it is not supported on some browsers, I used jquery datepicker as fallback and successfully managed to make it work.
Another thing I want is to display an error message if the user's selected date is valid. A date is valid if it is between 1900-01-01 and the current date.
Now, the problem is whenever I select a date for the first time, I am getting the error message even though I selected a valid date. And upon selecting a valid date for the second time, the error message disappears. On the third try, I selected an invalid date but the error doesn't show. On the fourth try, I selected a valid date but the error displays. To make it short, the validation applies to the previous input and not on the current input.
Below is the code on my controller:
var elem = document.createElement('input');
elem.setAttribute('type', 'date');
if ( elem.type === 'text' ) {
$('#contactBirthdate').datepicker({
dateFormat: "yy-mm-dd"
});
}
$scope.checkDate = function() {
console.log('Entered check date funtion');
var now = new Date();
var minDate = new Date('1900-01-01');
var inputDate;
if ( elem.type === 'text' ) {
$scope.appointment.birthday = new Date($( "#contactBirthdate" ).val());
console.log('input date not supported');
inputDate = new Date($scope.appointment.birthday);
} else {
inputDate = new Date($scope.appointment.birthday);
}
console.log('inputDate ' + inputDate);
if (inputDate < now && inputDate > minDate) {
$scope.isValidDate = true;
} else {
$scope.isValidDate = false;
}
console.log($scope.isValidDate);
};
And in my HTML
<div class="form-field">
<input name="contactBirthdate" type="date" min="1900-01-01" max="{{minAge | date: 'yyyy-MM-dd'}}" id="contactBirthdate" placeholder="Your Birthdate"
value="" class="full-width" ng-model="appointment.birthday" required="" step="1" ng-blur="checkDate()" onkeydown="return false">
<label ng-show="contactForm.contactBirthdate.$touched && !isValidDate" id="contactName-error" class="error" for="contactBirthdate">
Invalid Birthdate</label>
</div>
I really hope someone can help me with this one.

Daterangepicker change angularjs

I have a date range picker and I need to add a listener everytime i change the range of the values so i sent the startDate and endDate in my url to a restapi and then make a query to my databse with that valeus and get new rows.
My problem is with the listener.. I need something like "onChange" when i set new dates.
View:
<div class="form-group col-md-3 mb0" ng-if="timerange == 'custom'">
<div class="row">
<label class="col-sm-3 control-label pt7">Custom</label>
<div class="col-sm-9">
<input type="text" id="customrange" name="customrange" ng-model="parent.customrange" ng-change="applyOptions()" class="form-control" ui-jq="daterangepicker" ui-options="{format: 'YYYY/MM/DD',startDate: '{{startdate}}',endDate: '{{enddate}}', maxDate:'{{enddate}}'}" />
</div>
</div>
</div>
Controller:
var rangeSelector = document.getElementsByTagName('select')[1]; //1h 24h 1w custom
if(rangeSelector.value == 'custom'){
var datePicker = document.getElementById("customrange").getAttribute('ui-options');
var split = datePicker.split(",");
var startDate = split[1].split(': ')[1].replace(/["']/g, '');
var endDate = split[2].split(': ')[1].replace(/["']/g, '');
if (startDate !== undefined) {
url += '&startDate='+startDate;
}
if (endDate !== undefined) {
url += '&endDate='+endDate;
}
i tried 2 optiuons but i cant get into that code when i put a breakpoint on it..
$scope.$watch("customrange", function() {
console.log("I've changed : ");
});
and
rangeSelector.addEventListener("change", function(e){
if(rangeSelector.value == "custom"){
e.preventDefault();
customrange = document.getElementById("customrange");
customrange.addEventListener("change", function(){
startEndDate = controllerScope.getStartEndTimestamps();
});
}
}, false);
Anyone can help me please??
Image of problem
Updated:
The problem is that your $watch is not checking the correct model.
Your $watch should be called as follows:
$scope.$watch("parent.customrange", function(newValue, oldValue) {
console.log("I've changed : ");
});
To watch the object "parent":
$scope.$watch("parent", function(newValue, oldValue) {
console.log("I've changed : ");
}, true);
The true sets the optional objectEquality check.
Angular $watch Documentation:
When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.

ng-disabled in Angular not working

In My Angular UI I want to disable a submit button if
1) All the inputs are null or empty
2) If the endDate field is less than the startDate itself
What I did is ...
<input type="submit" class="btn btn-default pull-right" style="width:100px;" value="Submit"
ng-disabled="groupMembershipUserInputForm.$invalid || !(!!groupmembership.chapterCode || !!groupmembership.groupCode ||
!!groupmembership.groupName || !!groupmembership.createdBy ||
!!groupmembership.createdDate || !!groupmembership.startDate ||
!!groupmembership.endDate || !!groupmembership.losCode
|| groupmembership.compareAgainstStartDate(groupmembership.endDate) )" />
All the strings empty/null checks are working fine except the date compare check .
In my controller the method looks like
$scope.groupmembership.compareAgainstStartDate = function (item) {
var startDate = $filter('date')(new Date($scope.groupmembership.startDate), 'MM/dd/yyyy');
var endDate = $filter('date')(new Date($scope.groupmembership.endDate), 'MM/dd/yyyy');
if (endDate < startDate) {
$scope.groupmembership.toggleInvalidInput = true;
}
else
$scope.groupmembership.toggleInvalidInput = false;
return $scope.groupmembership.toggleInvalidInput;
};
It is being hit , but I don't know why the disabling not happening if the date compare fails .
Please help me .
So first :
All the inputs are null or empty
For this just add a required to all your input/select/...
If you do so groupMembershipUserInputForm.$invalid will be true if one of the required fields is not filled.
This will simplify greatly you ng-disabled to the following :
ng-disabled="groupMembershipUserInputForm.$invalid ||
groupmembership.compareAgainstStartDate(groupmembership.endDate)"
This is a first valid working step. Now if you want to go further you could create a directive and have something like :
<input ng-model="afterDate" date-greater-than="beforeDate"/>
This will be usefull if you have other forms than need this. If you're interested to do this i suggest you to google something like "angular js custom validation form directive" and if you have trouble with that directive, after trying on your own, come back to us into another question.
FInally if you master custom validation form you could use angular-message. it's a little addon specifically designed to display error from forms.
Here is a sample code from https://scotch.io/tutorials/angularjs-form-validation-with-ngmessages :
<form name="myForm">
<input
type="text"
name="username"
ng-model="user.username"
ng-minlength="3"
ng-maxlength="8"
required>
<div ng-messages="userForm.name.$error">
<p ng-message="minlength">Your name is too short.</p>
<p ng-message="maxlength">Your name is too long.</p>
<p ng-message="required">Your name is required.</p>
<p ng-message="myCustomErrorField">Your name is <your custom reason></p>
</div>
<input type="submit" ng-disabled="myForm.$invalid"/>
</form>
Your logic pretty much right, I have doubt on your $scope.groupmembership.startDate and $scope.groupmembership.endDate because if I provide correct dates, then it is working as expected. Can you please try by providing some constant date to verify whether your function is behaving properly or not. For me it is working fine with actual date values.
$scope.startDate = $filter('date')(new Date("07/02/2016"), 'MM/dd/yyyy');
$scope.endDate = $filter('date')(new Date("0710/2016"), 'MM/dd/yyyy');
In your example dates are string type so you may not get correct result. To compare date first convert it to time using getTime() that will give you exact result. No need to use filter for date check.
just use like:
$scope.groupmembership.compareAgainstStartDate = function () {
var startDate = new Date($scope.groupmembership.startDate);
var endDate = new Date($scope.groupmembership.endDate);
if (endDate.getTime() < startDate.getTime()) {
$scope.groupmembership.toggleInvalidInput = true;
}
else
$scope.groupmembership.toggleInvalidInput = false;
return $scope.groupmembership.toggleInvalidInput;
};
Just convert startdate and enddate to milliseconds, and compare them.
Try the below code once:
$scope.groupmembership.compareAgainstStartDate = function () {
var startDate = new Date($scope.groupmembership.startDate).getTime();
var endDate = new Date($scope.groupmembership.endDate).getTime();
if (endDate < startDate) {
$scope.groupmembership.toggleInvalidInput = true;
} else {
$scope.groupmembership.toggleInvalidInput = false;
}
return $scope.groupmembership.toggleInvalidInput;
};

How to pass date id from one jsp to another jsp page

I am calculating the price of a ticket with discount on weekdays and weekends based on the time duration.So, i gave inputs of duration and date using datepicker plugin which is in Above Page. For this i am getting proper result.But i have to create two different jsp pages(date.jsp and cal.jsp).
In 1st jsp page(date.jsp) i am selecting date using datepicker. And in 2nd jsp page(cal.jsp)
I have written a method ->[caluculate(#dateid,#duratiionid)] to calulate the price by taking inputs as time duration.
Here My Question is how shall i pass [#dateid] from 1st jsp page(date.jsp) to 2nd jsp page(cal.jsp)
so that i can pass both the id's in this method->[caluculate(#dateid,#duratiionid)].
<div id="container">
<div id="form">
<form id="book_court">
<div class="fieldset">
<fieldset>
<legend class="visuallyhidden">Booking Details</legend>
<h2>Booking Details</h2>
<p>
<label for="date">Date<br/><span id="dateNote">Firefox does not have a HTML5 datepicker yet.</span></label>
<input type="date" name="date" id="date" min="today" required />
</p>
<p>
<label for="tickets_duration"> Hours</label>
<input type="number" min="1" name="tickets_duration" id="tickets_duration" required />
</p>
<p>
<label>Total Price</label>
<span id="total_price">(enter data first)</span>
</p>
<div id="submit_wrapper">
<input type="submit" id="submit" value="Book Court" />
</div>
</fieldset>
</div>
</form>
</div>
</div>
<script id="worker" type="javascript/worker">
self.onmessage = function msgWorkerHandler(event){
var jsonString = event.data;
var day = jsonString.day;
var tickets_duration = jsonString.tickets_duration;
// set price of each hours as Rs. 200 and 300
var totalPriceOnWeekday = tickets_duration * 200;
var totalPriceOnWeekends=tickets_duration * 300;
// 10% discount if on weekday and 15% on weekends
if(day > 0 && day < 6){
totalPriceOnWeekday = totalPriceOnWeekday - 0.10 * totalPriceOnWeekday;
postMessage("₹ " + totalPriceOnWeekday);
}else if(day == 0 || day == 7){
totalPriceOnWeekends = totalPriceOnWeekends - 0.15 * totalPriceOnWeekday;
postMessage("₹ " + totalPriceOnWeekends);
}
}
</script>
<script>
$(document).ready(function(){
// first check the movies already book
// apply jQuery UI Redmond theme to 'Book Tickets' button
$("#submit").button();
// calculateTotalPrice on keyup or on change of movie/date/tickets
$("#date, #tickets_duration").change(calculateTotalPrice);
// on form submit
$("#book_court").submit(function(event){
// prevent on submit page refresh
event.preventDefault();
// check locally stored data
// clear the form
$( '#book_court' ).each(function(){
this.reset();
});
// reset (enter data first) message
$("#total_price").html("(enter data first)");
// update movies booked list
});
// set minimum date in datepicker as today
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("date")[0].setAttribute('min', today);
});
function calculateTotalPrice(){
if($("#tickets_duration").val() != "" && $("#date").val() != ""){
if(window.Worker){
// create web worker
var blob = new Blob(
[document.querySelector("#worker").textContent],
{type: 'text/javascript'});
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(event){
$("#total_price").html(event.data);
}
worker.onerror = function(errorObject){
$("#total_price").html("Error: " + errorObject.message);
}
var date = new Date($('#date').val());
// get day
var day = date.getDay();
// get number of booked shows
// send JSON data to worker
var jsonData = {'day': day, 'tickets_duration': Number($("#tickets_duration").val())};
worker.postMessage(jsonData);
}
}
}
</script>
If you want to share a value cross-pages, you can use cookie to store the value. Another option is localStorage/sessionStorage if you are using HTML5.
So, in the first page (date.jsp), when user select a date, you can store that selection to cookie, in the second page (cal.jsp) you can read that value from cookie and then do your calculation.
I suppose that you are able to post the date string back to servlet. In the servlet, you are using that date string to check for ticket validity. You just don't know how to check if the date is weekday or weekends. If so you can you the java.util.Calendar for that purpose.
EDITED
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date yourDate = formatter.parse(dateInString);
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

Categories

Resources