Tempus Dominus minDate counld not parse - momentjs

First time using Tempus Dominus Datetimepicker for Bootstrap 4.
In my code I have:
var dateFormat = 'DD-MM-YYYY';
var CurrDate = '27-06-2018';
var MinDate = '27-06-1918';
var MaxDate = '27-06-2018';
I then convert the dates to moment objects:
dateMin = moment(CurrDate, dateFormat);
dateMin = moment(MinDate, dateFormat);
dateMax = moment(MaxDate, dateFormat);
I can see the moment objects in console.log(), dates are correct.
Moment {_isAMomentObject: true, _i: "27-06-2018", _f: "DD-MM-YYYY", _isUTC: false, _pf: {…}, …}
Moment {_isAMomentObject: true, _i: "27-06-1918", _f: "DD-MM-YYYY", _isUTC: false, _pf: {…}, …}
Moment {_isAMomentObject: true, _i: "27-06-2018", _f: "DD-MM-YYYY", _isUTC: false, _pf: {…}, …}
I then initialise the datetimepicker like this:
// Initialize Stand Alone datetimepicker
$('#myDiv').datetimepicker({
format: dateFormat,
date: dateCurr,
minDate: dateMin,
maxDate: dateMax,
});
But it fails with:
minDate() Could not parse date parameter: NaN
Why is the datepicker not happy with a moment? The instructions here say it should work. Have I missed / messed up something?

Your code seems to be working fine:
$(function() {
var dateFormat = "DD-MM-YYYY";
var CurrDate = "27-06-2018";
var MinDate = "01-06-2018";
var MaxDate = "27-06-2018";
dateCurr = moment(CurrDate, dateFormat);
dateMin = moment(MinDate, dateFormat);
dateMax = moment(MaxDate, dateFormat);
$("#datetimepicker1").datetimepicker({
format: dateFormat,
date: dateCurr,
minDate: dateMin,
maxDate: dateMax,
});
});
<link href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/css/tempusdominus-bootstrap-4.min.css" rel="stylesheet"/>
<div class="container mt-3">
<div class="row">
<div class="col">
<div class="form-group">
<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1" />
<div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js"></script>
Check that you included:
jQuery
moment.js
tempusdominus-bootstrap-4.js

Related

Moment.js: Convert datetime string into UTC

I'm trying to use moment.js library to convert a datetime string into a local UTC. How do I do that?
html:
<div style="float:left; margin-right: 5em;">
<label id="startDateTimeLabel">Start DateTime</label>
<div class="input-group input-append date" id="startDateTime" style="width:300px;">
<input type="text" class="form-control">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
<input id="ButtonConnect" class="btn btn-primary" type="button" value="Connect" onclick="ButtonGetSelectedDate();" />
<script>
const startPicker = new tempusDominus.TempusDominus(document.getElementById('startDateTime'));
var tStartDatetime = startPicker.dates.picked;
//the below line seems to be a javascript datetime;
console.log('tStartDatetime : ' + tStartDatetime ); //this is the format: Sat May 15 2021 12:30:00 GMT-0400 (Eastern Daylight Time)
var tStart = moment(tStartDatetime ).valueOf();
console.log('tStart : ' + tStart ); //this prints Nan on the console
</script>
this is what I did and it seems to work ok.
tStart = moment(new Date(tStartDatetime)).valueOf();

Angular-input number from number pad to clicked textbox

I am new in Angular and
I am facing a problem right now that is, I have a number pad and some textboxes.
I have to input to the particular textbox from number pad.
Here is the Code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = ''
});
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button id="btn1" ng-click="count = count + 1">1</button>
<button id="btn2" ng-click="count = count + 2">2</button>
<label>Textbox1</label><input type="text" id="Textbox1" value="{{count}}"/>
<label>Textbox2</label><input type="text" id="Textbox2" value="{{count}}"/>
</div>
</body>
</html>
Now if I click on Textbox1 then click on button 1 or 2 text should be only on Textbox1 not textbox2
is it possible to bind value to value using ng-click like this
function on controller
$scope.change = function(evt) {
evt.target.value={{count}};
alert(evt.target.id)
html
<label>Textbox1</label><input type="text" id="Textbox1" value="{{count}}" ng-click="change($event)"/>
<label>Textbox2</label><input type="text" id="Textbox2" value="{{count}}" ng-click="change($event)"/>
or some other way
I'm not 100% sure I understood what you want to do, but if I'm right, this should do what you want:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.field1count;
$scope.field2count;
$scope.selectedField = 0;
$scope.calculateField = function(amount){
var result = $scope.count + amount;
$scope.count = result;
if($scope.selectedField == 1){
$scope.field1count = result;
} else if($scope.selectedField == 2){
$scope.field2count = result;
}
}
});
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button id="btn1" ng-click="calculateField(1)">1</button>
<button id="btn2" ng-click="calculateField(2)">2</button>
<label>Textbox1</label>
<input type="text" id="Textbox1" ng-focus="selectedField = 1" ng-model="field1count"/>
<label>Textbox2</label>
<input type="text" id="Textbox2" ng-focus="selectedField = 2" ng-model="field2count"/>
</div>
</body>
</html>
If you want the two input fields to display different values, you need to actually assign them different values, as angular's two-way-binding means the value will be updated in both the model and the controller simultaneously.
Ng-focus can also be replaced by ng-click in this case, if you prefer using that. Ng-focus is triggered when the input field gains focus (When you use, for example, the tab key to reach the field, this will also be triggered), while ng-click does so when the field is clicked upon.
In this example ng-model="field1count" can also be replaced with value="{{field1count}}", as you did in your example, but the use of ng-model is more appropriate to the use of angular.
Working snippet:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.field1count;
$scope.field2count;
$scope.selectedField = 0;
$scope.calculateField = function(amount){
var result = $scope.count + amount;
$scope.count = result;
if($scope.selectedField == 1){
$scope.field1count = result;
} else if($scope.selectedField == 2){
$scope.field2count = result;
}
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button id="btn1" ng-click="calculateField(1)">1</button>
<button id="btn2" ng-click="calculateField(2)">2</button>
<label>Textbox1</label><input type="text" id="Textbox1" ng-click="selectedField = 1" ng-model="field1count"/>
<label>Textbox2</label><input type="text" id="Textbox2" ng-click="selectedField = 2" ng-model="field2count"/>
</div>
</body>
</html>
You should use two separeted ng-model on your input if what you want is to output two different datas.
But I'm not really sure of what you want to do here .. Can you try to explain it a bit more ?

Datepicker not working in asp.net MVC

I am using .net MVC. This is my razor view of create a Bill which have a property Due Date. I want to use date picker in my code but it's not working when i use following code:
<div class="form-group">
#Html.LabelFor(model => model.DueDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.DueDate, new { id = "datepicker" })
#Html.ValidationMessageFor(model => model.DueDate)
</div>
</div>
<script type="text/javascript">
$(document).ready(function () { $("#datepicker").datepicker({ });});
</script>
So I changed the code to following then it started working but how can I pass the duedate value to controller the above code automatically attaches the due date value to object but the below code can't.
<div class="form-group">
#Html.LabelFor(model => model.DueDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="date" id="datepicker" class="form-control"/> //Changing
#Html.ValidationMessageFor(model => model.DueDate)
</div>
</div>
<script type="text/javascript">
$(document).ready(function () { $("#datepicker").datepicker({ });});
</script>
The code in your first snippet uses a date time picker control provided by jQuery UI library.To make it work you need to add a reference to the following files in this order:
jQuery.js
jQueryUI.js
jQueryUI.css
So your final code should look something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet">
<script type="text/javascript">
$(function () {
$("#datepicker").datepicker();
});
</script>
The code in your second snippet uses an HTML 5 input of type date, as was pointed out by Stephen.This automaticallly makes the input a date time picker if it's supported by the browser.
The reason the second snippet wasn't working is that the binding in MVC happens on the name property.Since your C# property is called DueDate you need to add name="DueDate" to the input element.
Change this line:
<input type="date" id="datepicker" class="form-control"/>
To this:
<input name="DueDate" type="date" id="datepicker" class="form-control"/>

How can i re-render a template embedded in another template

currently i'm working on a project for monitoring solar power stations. And i have a panel template that embedded in dashboard template.
and panel template has its own subscribe, but it seems not reactive? how can i make the panel template reactive?? Thanks.
<template name="Dashboard">
<div class="container-fluid">
<div class="row">
{{#if Template.subscriptionsReady}}
{{#each station in stations}}
{{> StationPortlet station=station}}
{{/each}}
{{else}}
Loading...
{{/if}}
</div>
</div>
</template>
And for Dashboard.js
Template.Dashboard.helpers({
stations: function() {
return Stations.find();
}
});
Template.Dashboard.onCreated(function () {
this.subscribe('allStations');
});
code for Station Panel template
<template name="StationPortlet">
<div class="col-md-6 col-sm-12">
{{#if Template.subscriptionsReady}}
{{#with portlet}}
<!--<div class="panel panel-b-accent m-t-sm panel-filled panel-c-success">-->
<div class="panel panel-filled panel-c-{{indicator}}">
<div class="panel-heading" style="color:#f6a821">
{{> panelTools }}
<!-- <a style="display:block" href="{{pathFor '/dashboard/:id' id=this.id.toHexString}}">{{Name}}</a> -->
<h4 style="color:#f6a821">{{Name}}</h4>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6 col-xs-6">
<div class="panel panel-filled">
<div class="panel-body">
<h2 class="m-b-none">
{{Capacity}} <span class="slight"> KW</span>
</h2>
<div class="small">設置容量</div>
</div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="panel panel-filled">
<div class="panel-body">
<h2 class="m-b-none" style="color:#f6a821">
{{energyPerKW}} <span class="slight"></span>
</h2>
<div class="small">每 KW 發電度數</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-6">
<div class="panel panel-filled">
<div class="panel-body">
<h2 class="m-b-none">
{{EnergyToday}}
<span class="slight"><i class="fa fa-play fa-rotate-270 text-warning"> </i> KWh</span>
</h2>
<div class="small">Energy Today</div>
</div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="panel panel-filled">
<div class="panel-body">
<h3 class="m-b-none">
{{EnergyLifetime}} <span class="slight"><i class="fa fa-play fa-rotate-270 text-warning"> </i> KWh</span>
</h3>
<div class="small">Energy Lifetime</div>
</div>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="slight m-t-sm"><i class="fa fa-clock-o"> </i> Updated: <span class="c-white">{{update}}</span> </div>
</div>
</div>
{{/with}}
{{else}}
<div class="center-block">
{{>LoadingCircle}}
</div>
{{/if}}
</div>
</template>
and for javascript
portlet: function() {
// var station = new ReactiveVar(Template.currentData().station);
var station = this.station;
var entry = {};
entry.id = station._id;
entry.Name = station.Name;
entry.EnergyToday = 0;
entry.EnergyLifetime = 0;
entry.update = null;
entry.Capacity = 0;
entry.indicator = 'success';
//console.log(station);
var inverters = Inverters.find({ Station: station._id, Enabled: true });
var inverter_indicator = 'success';
inverters.forEach(function(inverter) {
entry.Capacity += inverter.Capacity;
//console.log(inverter);
// get the latest logs for this inverter for today
var inverter_logs = InverterLogs.find({ Station: station._id, Inverter: inverter._id }, { sort: { created_at: -1 }, limit: 1 });
inverter_logs.forEach(function(log) {
entry.EnergyToday += log.EnergyToday.value;
entry.EnergyLifetime += log.EnergyLifetime.value;
entry.update = log.created_at;
//console.log(log);
if (log.Inverter_Status.indicator !== 'success') {
console.log('inverter status !=== success');
if (log.Inverter_Status.indicator === 'warning' && inverter_indicator !== 'danger') {
inverter_indicator = 'warning';
}
if (log.Inverter_Status.indicator === 'danger') {
inverter_indicator = 'danger';
}
}
});
});
entry.indicator = inverter_indicator;
// Compare time if latest logs is more than 20 mins or 45 mins. and if yes, set indicator to warning or danger
var twentyMins = 1000*60*20;
var fourtyfiveMins = 1000*60*45;
var latestUpdateIndicator = 'success';
if ((Date.now()-entry.update) > twentyMins) {
// if the date of lastes log is more than 20 mins earlier, set indicator warning
latestUpdateIndicator = 'warning';
if ((Date.now()-entry.update) > fourtyfiveMins) {
latestUpdateIndicator = 'danger';
}
}
if (latestUpdateIndicator !== 'success') {
if (latestUpdateIndicator === 'warning' && entry.indicator === 'success') {
entry.indicator = 'warning';
} else if (latestUpdateIndicator === 'danger' && (entry.indicator === 'success' || entry.indicator === 'warning')) {
entry.indicator = 'danger';
}
}
// if the date of lastes log is more than 20 mins earlier, set indicator warning
//entry.update = moment(entry.update).format('LLL');
entry.update = moment(entry.update).fromNow();
entry.EnergyToday = entry.EnergyToday.toFixed(2);
entry.energyPerKW = (entry.EnergyToday/entry.Capacity).toFixed(2);
entry.EnergyLifetime = entry.EnergyLifetime.toFixed(2);
//entry.update = moment(update).format('LLL');
return entry;
}
Template.StationPortlet.onCreated(function () {
var station = Template.currentData().station;
var self = this;
var now = moment().toDate();
var today = moment(4, "HH").toDate();
Deps.autorun(function() {
self.subscribe('invertersByStation', station._id);
self.subscribe('inverter_logs_ByStation', station._id, today, now, 100);
});
And i'm trying to find good explaination about Blaze render life cycle, if you have any suggestion, plz let me know :)
Here is Publish.js
Meteor.publish('allStations', function () {
var user = Meteor.users.findOne({_id:this.userId});
var client = Clients.findOne({ name: Roles.getGroupsForUser(user)[0] });
if (Roles.userIsInRole(user, 'super-admin', Roles.GLOBAL_GROUP)) {
return Stations.find();
}
else if (Roles.userIsInRole(user, 'client', client.name)) {
console.log('user is client');
var subscribeStations = client.subscribeStations;
return Stations.find({ _id: {$in: subscribeStations} });
} else {
console.log('user is not defined');
return [];
}
});
Meteor.publish('invertersByStation', function (stationID) {
return Inverters.find({ Station: stationID });
});
Meteor.publish('inverter_logs_ByStation', function (stationID, greaterThan, lessThan, limit) {
return InverterLogs.find({ created_at: {$gte: greaterThan, $lte: lessThan}, Station: stationID}, { sort: {created_at: -1}, limit: limit});
});
Your problem come from your helper portlet witch is reactive but don't refer any data reactive source.
What happend?
Just understand helpers natively wrap a Tracker.autorun, witch allow them to rerun when a reactive data change on their scope.
On your helper portlet, you are doing some operations on locally instanciated object entry. However, nothing on your helper is able to trigger reactive rerun.
You should probably look on WHICH CHANGE you want the helper to be rerun.
Once you know that, just use this data as reactive data source (native as Mongo cursor, or wrapped on ReactiveVar).

Autocomplete generate multiple markers

My goal is to have several input fields with Autocomplete functionality and each input will generate a marker on the map. I then need the map to zoom in to contain all of the markers. I have this working partially, without the Autocomplete functionality. I have tried adding the Google Maps API Places Autocomplete code to my for loop, but to no avail. It gives autocomplete functionality to all the input fields but only places a marker for the last input.
Any help/insight/guidance is appreciated.
Here is my code, the autocomplete is currently deleted since I couldn't get it to work.
<div class="container-fluid">
<div class="row-fluid">
<div class="span4 well">
<div id="locations">
<form>
<label>Location 0</label>
<input id="address0" type="text" size="50" >
<button id="clearField0">Clear</button>
<div class="panel">
<label>Location 1</label>
<input id="address1" type="text" size="50">
<button id="clearField0">Clear</button>
</div>
<div class="panel">
<label>Location 2</label>
<input id="address2" type="text" size="50">
<button id="clearField0">Clear</button>
</div>
</form>
</div>
<button id="addField">+</button>
<button id="deleteField">-</button>
<button id="submit">Submit form</button>
</div>
<div class="span8">
<div id="map-wrapper">
<div id="google-map"></div>
</div>
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCtNo_o0u8wYeqgiFF-KpvAtEy18T-PvAo&sensor=false&callback=createMap"></script>
<script type="text/javascript">
var inputFields = parseInt($('form input').size());
var markers = [];
var createMap = function() {
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var myOptions = {
center : new google.maps.LatLng(35.9081, -78.8628), //center to RTP
zoom : 12,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById("google-map"), myOptions);
$("#submit").on("click", function() {
setAllMap(null);
markers.pop();
for (i=0; i<inputFields; i++) {
var location = $("#address" + i).val();
geocoder.geocode( {'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
latlngbounds.extend(results[0].geometry.location);
map.fitBounds(latlngbounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
};
});
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
$('#addField').click(function(){ //add input field to bottom of form
$('form').append('<div class="panel"><label>Location '+ inputFields +'</label><input id="address'+ inputFields +'" type="text" size="50"><button id="clearField'+ inputFields +'">Clear</button></div>');
inputFields++;
});
$('#deleteField').click(function(){ //delete last input field
$('.panel').last().remove();
inputFields--;
});
};
</script>
My first problem was including the places library in the API reference. Following that, I simply needed two lines of code from Google's Places Autocomplete example page, as opposed to the entire script they offer:
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
These two lines in my for loop solved the problem. Thanks again to Dr. Molle whose comment made me rethink what code I needed.

Resources