On change of value in datetimepicker it should update another text area - javascript

I am new to bootstrap and trying to use it and I am trying to do below mentioned.
My datetime picker control 1
<div class='input-group date' id="reportdate">
<input type='text' class="form-control" value="#Model.ReportDate.ToString("dd/MM/yyyy")"/>
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
My date time picker control 2
<div class='input-group date' id="fromdate">
<input type='text' class="form-control" value="#Model.RecievedFrom.ToString("dd/MM/yyyy")"/>
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
What I am trying to do?
On change of the value from my date time picker control 1 it should change the value in datetimepiker control2.
What I did?
My main.js class which is handling all these functions.
var main = main || {};
main.functions = function() {
function changeDates() {
***// I am trying to change the value of my datetime picker control2 here.
var val = $(this).val;
alert(val);***
}
return {
changeDates: changeDates
};
}();
main.Loader = function () {
//-- Entry point
function init() {
var $body = $("body");
loadDatePickers($body);
loadTimePickers($body);
}
//-- Load date time pickers
function loadDatePickers($context) {
var $datePickers = $context.find(".date");
if ($datePickers.length) {
$datePickers.each(function () {
$(this).datetimepicker({ language: 'en-gb', pickTime: false });
if ($(this).attr("id") == "reportdate") {
$(this).change(function () {
main.functions.changeDates();
});
}
});
}
}
function loadTimePickers($context) {
var $timePickers = $context.find(".time");
if ($timePickers.length) {
$timePickers.each(function () {
$timePickers.datetimepicker({ language: 'en-gb', pickDate: false });
});
}
}
return {
init: init
};
}();
$(document).ready(function () {
main.Loader.init();
});
Any help would be much appreciated.

You can use .change event for that,
$("#reportdate").find(".form-control").change(function () {
$("#fromdate").find(".form-control").val($(this).val());
});

Related

Hide/Show an element automatically( not using a keyup() or click ) when an input field is entered/selected a value

I have an <input> tag in my form that takes a value from Bootstrap Datepicker.
<div class="wrapper">
<div class="form-group">
<label>Select Date</label>
<div class="input-group">
<input name="date_info" type="text" class="form-control datepick validate_date" placeholder="Date" readonly>
</div>
<small class="validate_date_error">This field is mandatory!</small>
<small class="validate_date_success">This is Fine!</small>
</div>
<button class="next">Next</button>
</div>
I'm trying to achieve a functionality as in, On click of .next button, if date is not selected or is empty, I'm displaying .validate_date_error.
If date is selected, without a click or [Enter] key, I want to show .validate_date_success.
Following is my JS
$(function() {
$('.datepick').datepicker({
autoclose: true,
format: 'dd-mm-yyyy'
});
});
$(".next").click( function() {
var check_date = $(".validate_date").val();
if( check_date === "" ){
$(this).parent().find('.validate_date_error').show();
}else {
$(this).parent().find('.validate_date_error').hide();
$(this).parent().find('.validate_date_success').show();
}
});
If anyone could solve this for me, it'll be of gret help.
I have updated my code here JS Fiddle
On selecting a value from datepicker, you can use the onchange event,
$('input[name=date]').change(function() {
var check_date = $(".validate_date").val();
$('.validate_date_error').hide();
if(check_date === ""){
$('.validate_date_success').hide();
}else{
$('.validate_date_success').show();
}
});
Hope this solves your problem.
You should use the function change given by JQuery. This function is called everytime the value in an input changed, so it is perfect for you.
You could do something like this, first of all set an id in your input something like that :
<input id="date" name="date_info" type="text" class="form-control datepick validate_date" placeholder="Date" readonly>
then in you js file add the change method :
$('#date').change(function () {
if($(this).val() !== '') //If a date had been picked
{
//show success message
}
else
{
//show error message
}
})
Of course this is the basic, you can improve the condition to fit as much as you want.
Here is your fiddle http://jsfiddle.net/zNbUT/750/
Hope it helps you
How about this, using the .on(event, callback) method
$(function() {
$('.datepick').datepicker({
autoclose: true,
format: 'dd-mm-yyyy'
});
});
$("input[name='date']").on('change', function (e) {
if (e.target.value) {
$('.validate_date_error').hide();
$('.validate_date_success').show();
} else {
$('.validate_date_error').show();
}
})
$(".next").click( function() {
var check_date = $(".validate_date").val();
if( check_date === "" ){
$(this).parent().find('.validate_date_error').show();
}else {
$(this).parent().find('.validate_date_error').hide();
$(this).parent().find('.validate_date_success').show();
}
});

Format date on bootstrap datetimepicker

I am using the Bootstrap 3 Date/Time Picker (https://github.com/Eonasdan/bootstrap-datetimepicker) and I have problems
formatting the date
<input type="text" id="fmEndDate" class="form-control input-sm"
datetimepicker
format="DD-MM-YYYY hh:mm"
ng-model="workRequest.EndDate"
placeholder="..."
name="fmEndDate"
required
ng-disabled="isDisabled">
But the value is being display as MM/DD/YYYY hh:mm AM
i want 31-12-2017 23:59 for new year eve timestamp
This is my directive
"use strict";
angular.module("datetimepicker", [])
.provider("datetimepicker", function () {
var defaultOptions = { };
this.setOptions = function (options) {
defaultOptions = options;
};
this.$get = function () {
return {
getOptions: function () {
return defaultOptions;
}
};
};
})
.directive("datetimepicker", [
"$timeout",
"datetimepicker",
function ($timeout,datetimepicker) {
var defaultOptions = datetimepicker.getOptions();
return {
require : "?ngModel",
restrict: "AE",
scope : {
datetimepickerOptions: "#"
},
link : function ($scope, $element, $attrs, ngModelCtrl) {
var passedInOptions = $scope.$eval($attrs.datetimepickerOptions);
var options = jQuery.extend({}, defaultOptions, passedInOptions);
$element
.on("dp.change", function (e) {
if (ngModelCtrl) {
$timeout(function () {
ngModelCtrl.$setViewValue(e.target.value);
});
}
})
.datetimepicker(options);
function setPickerValue() {
var date = options.defaultDate || null;
if (ngModelCtrl && ngModelCtrl.$viewValue) {
date = ngModelCtrl.$viewValue;
}
$element
.data("DateTimePicker")
.date(date);
}
if (ngModelCtrl) {
ngModelCtrl.$render = function () {
setPickerValue();
};
}
setPickerValue();
}
};
}
]);
Any ideas?
As shown in the bootstrap3 docs you can define custom formats in JavaScript:
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker3'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker3').datetimepicker({
format: 'your desired Formatting style'
});
});
</script>
</div>
</div>
Even more simple:
$("#fmEndDate").datetimepicker({format: 'dd-mm-yyyy hh:ii'});
Sidenote: Be careful with Date/Time formatting:
As for AngularJS HH format will result in hours as 00-23. While in Bootstrap3 which you are also using HH will result in hours as 01-12.
I highly suggest you to use a library like MomentJS which is doing the troublesome work for you.
Regards,
Megajin

Angularjs. TypeError: Cannot read property 'apply' of undefined

I have angularjs app with a form that has a dropdownlist and and a datetimepicker.
When I change the dropdownlist I want to update the date displayed in the datepicker.
I get the following error when I change selected item in the dropdownlist
TypeError: Cannot read property 'apply' of undefined
at HTMLInputElement.<anonymous> (bootstrap-datetimepicker.min.js:2)
at Function.each (jquery-3.1.1.min.js:2)
at r.fn.init.each (jquery-3.1.1.min.js:2)
at r.fn.init.a.fn.datetimepicker (bootstrap-datetimepicker.min.js:2)
at m.$scope.SymbolChanged (moduleConfigformController.js:29)
at fn (eval at compile (angular.js:15197), <anonymous>:4:159)
at m.$eval (angular.js:18017)
at angular.js:25775
at Object.<anonymous> (angular.js:28600)
at q (angular.js:357)
This is the offending line of code:
$("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
Here is my controller:
mainApp2.controller("moduleConfigformController",
function moduleConfigformController($scope, moduleConfigformService, $uibModalInstance) {
$scope.close = function (e) {
$uibModalInstance.dismiss();
e.stopPropagation();
};
$scope.formDebug = "loaded";
var settingsPromise = moduleConfigformService.simulationsettings();
settingsPromise.then(function (settings) {
$scope.simulationsettings = settings;
$scope.symbols = $scope.simulationsettings.symbols;
$scope.intervals = $scope.simulationsettings.intervals;
}).catch(function (error) {
throw error;
});
$scope.SymbolChanged = function () {
console.log("Symbol ddl changed");
console.log("New value is " + $scope.simulationsettings.Symbol);
// hardcoded date
// TODO: Find StartDate and EndDate where Symbol = $scope.simulationsettings.Symbol
$scope.simulationsettings.StartDate = "24/12/2014 8:26 PM";
// Display the new date in the datetimepicker
// This line produced the TypeError
$("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
console.log("startdate is " + $scope.simulationsettings.StartDate);
console.log("startdate is " + $scope.simulationsettings.EndDate);
}
$scope.submitConfigForm = function () {
console.log("configform submitted");
var startDate = $scope.simulationsettings.StartDate;
var endDate = $scope.simulationsettings.EndDate;
var symbol = $scope.simulationsettings.Symbol;
var interval = $scope.simulationsettings.Intervals;
$scope.formDebug = "StartDate: " + startDate + " EndDate: " + endDate + " Symbol: " + symbol + " Interval: " + interval;
}
});
Here is my form:
<form name="configForm" ng-submit="submitConfigForm()">
<div class="modal-header" style="text-align:center">
<h3 class="modal-title">Configure</h3>
<div style="margin-top:10px">
<button tabindex="100" class="btn btn-success pull-left" type="submit" ng-class="{'btn-primary':configForm.$valid}">Start analysis</button>
<button class="btn btn-warning pull-right" ng-click="close($event)">Close</button>
</div>
</div>
<div class="modal-body">
<div class="col-sm-6" style="width: 100%;">
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-3">Symbol</label>
<div class="col-sm-9">
<select ng-model="simulationsettings.Symbol" ng-change="SymbolChanged()" name="fmSymbols" id="fmSymbols">
<option ng-repeat="item in symbols" value="{{item.Symbol}}">{{item.Symbol}}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">start date</label>
<div class="col-sm-9">
<input type="text" id="fmStartDate" class="form-control input-sm"
datetimepicker
ng-model="simulationsettings.StartDate"
placeholder="..."
name="fmStartDate">
</div>
</div>
</div>
form debug: '{{formDebug}}'
</div>
</div>
The datetimepicker directive
"use strict";
angular.module("datetimepicker", [])
.provider("datetimepicker", function () {
var defaultOptions = {};
this.setOptions = function (options) {
defaultOptions = options;
};
this.$get = function () {
return {
getOptions: function () {
return defaultOptions;
}
};
};
})
.directive("datetimepicker", [
"$timeout",
"datetimepicker",
function ($timeout,datetimepicker) {
var defaultOptions = datetimepicker.getOptions();
return {
require : "?ngModel",
restrict: "AE",
scope : {
datetimepickerOptions: "#"
},
link : function ($scope, $element, $attrs, ngModelCtrl) {
var passedInOptions = $scope.$eval($attrs.datetimepickerOptions);
var options = jQuery.extend({}, defaultOptions, passedInOptions);
$element
.on("dp.change", function (e) {
if (ngModelCtrl) {
$timeout(function () {
ngModelCtrl.$setViewValue(e.target.value);
});
}
})
.datetimepicker(options);
function setPickerValue() {
var date = options.defaultDate || null;
if (ngModelCtrl && ngModelCtrl.$viewValue) {
date = ngModelCtrl.$viewValue;
}
$element
.data("DateTimePicker")
.date(date);
}
if (ngModelCtrl) {
ngModelCtrl.$render = function () {
setPickerValue();
};
}
setPickerValue();
}
};
}
]);
Any idea how to update the datetimepicker so it displays the updated value?
You are updating the model here:
$scope.simulationsettings.StartDate = "24/12/2014 8:26 PM";
Then you try to set the datepickers value here:
$("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
But the datepicker has $scope.simulationsettings.StartDate as model. This is why you get the error. Angular is trying to call the digest cycle twice.
Your function should look like this:
$scope.SymbolChanged = function () {
console.log("Symbol ddl changed");
console.log("New value is " + $scope.simulationsettings.Symbol);
// hardcoded date
// TODO: Find StartDate and EndDate where Symbol = $scope.simulationsettings.Symbol
// the binding should be of the same type as your input, it means that the value returned from the datepicker must be a Date
$scope.simulationsettings.StartDate = new Date("24/12/2014 8:26 PM");
// This line is useless, the datepicked model is binded to $scope.simulationsettings.StartDate
// $("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
console.log("startdate is " + $scope.simulationsettings.StartDate);
console.log("startdate is " + $scope.simulationsettings.EndDate);
}
But since you are using an input type="text" we need more information on the datetimepicker directive that you are using.
your are trying to put a date object in text field which may work if you're not using a date-picker
1/ change your input type to type date or change this $("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
to this $("#fmStartDate").datetimepicker("setDate", $scope.simulationsettings.StartDate);
and it may work if your date-picker accepts this format "24/12/2014 8:26 PM"
2/ you may wanna check the date-picker documentation for the accepted format types

Asp.net MVC run javascript on button click

I kind of messed up the logic of my code, and I can't figure out how to fix it. I have a Bootstrap navtab panel that when the tabs are clicked, based on which tab is clicked it runs an MVC C# function in my controller. I actually need this to happen on a button click. SO the user enters a date into the datepicker, clicks submit, and then based on which tab is selected, a function will be run. How can I do this on a button click?
Here is my datepicker and button:
<div class="row spiff-datepicksection">
<div class="col-lg-6 pull-right">
<div class="col-sm-5 col-lg-offset-4">
<div class="form-group">
<div class="input-group date">
<input id="startDate" type="text" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="col-lg-3">
<input class="spiffdate-btn" type="submit" value="Submit" />
</div>
</div>
</div>
Here is my javascript:
<script>
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var wrongid = $('.tab-content .active').attr('id');
$('a[data-toggle="tab"]').removeClass("active");
$(this).addClass("active");
var correctid = $(this).data("id");
alert($('.tab-content .active')[0].outerHTML);
var startDate = $('#startDate').val();
if (correctid == "delayedspiff")
$.get("#Url.Action("DelayedSpiffDate", "Dashboard")", { startDate: startDate });
else
$.get("#Url.Action("InstantSpiffDate", "Dashboard")", { startDate: startDate });
});
</script>
And here is my controller if it is needed:
public ActionResult DelayedSpiffDate(DateTime startDate)
{
var available = _appService.GetFeatureStatus(1, "spiffDashboard");
if (!available)
return RedirectToAction("DatabaseDown", "Error", new { area = "" });
var acctId = User.AccountID;
//startDate = DateTime.Today.AddDays(-6); // -6
var endDate = DateTime.Today.AddDays(1); // 1
Dictionary<DateTime, List<SpiffSummaryModel>> dict = new Dictionary<DateTime, List<SpiffSummaryModel>>();
try
{
var properties = new Dictionary<string, string>
{
{ "Type", "DelayedSpiff" }
};
telemetry.TrackEvent("Dashboard", properties);
dict = _reportingService.GetDailyDelayedSpiffSummaries(acctId, startDate, endDate);
}
catch (Exception e)
{
if (e.InnerException is SqlException && e.InnerException.Message.StartsWith("Timeout expired"))
{
throw new TimeoutException("Database connection timeout");
}
var error = _errorCodeMethods.GetErrorModelByTcError(PROJID.ToString("000") + PROCID.ToString("00") + "001", "Exception Getting DelayedSpiff Dashboard View", PROJID, PROCID);
error.ErrorTrace = e.ToString();
_errorLogMethods.LogError(error);
return RedirectToAction("index", "error", new { error = error.MaskMessage });
}
var spiffDateModels = new List<DelayedSpiffDateModel>();
foreach (var entry in dict)
{
var spiffDateModel = new DelayedSpiffDateModel();
spiffDateModel.Date = entry.Key;
spiffDateModel.Carriers = new List<DelayedSpiffCarrierModel>();
foreach (var item in entry.Value)
{
var spiffCarrierModel = new DelayedSpiffCarrierModel();
spiffCarrierModel.Carrier = item.CarrierName;
spiffCarrierModel.CarrierId = item.CarrierId;
spiffCarrierModel.ApprovedSpiffTotal = item.ApprovedSpiffTotal;
spiffCarrierModel.EligibleActivationCount = item.EligibleActivationCount;
spiffCarrierModel.IneligibleActivationCount = item.IneligibleActivationCount;
spiffCarrierModel.PotentialSpiffTotal = item.PotentialSpiffTotal;
spiffCarrierModel.SubmittedActivationCount = item.SubmittedActivationCount;
spiffCarrierModel.UnpaidSpiffTotal = item.UnpaidSpiffTotal;
spiffDateModel.Carriers.Add(spiffCarrierModel);
}
spiffDateModels.Add(spiffDateModel);
}
spiffDateModels = spiffDateModels.OrderByDescending(x => x.Date).ToList();
return PartialView(spiffDateModels);
}
Any ideas on how to make this happen on a button click?
You can try to create a handler of the 'click' event, which should retrieve a valid identifier of the selected tab and send a GET request to the server.
$(".spiffdate-btn").click(function(){
var correctid = $(".tab-content .active").attr("id");
var startDate = $("#startDate").val();
if (correctid == "delayedspiff")
$.get("#Url.Action("DelayedSpiffDate", "Dashboard")", { startDate: startDate });
else
$.get("#Url.Action("InstantSpiffDate", "Dashboard")", { startDate: startDate });
});
I realize this is an old question, but I am struggling with a similar issue so I am looking at old questions.
I think I see your problem though:
<script>
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
Your script calls "on shown".
If you do not want it running when it is shown, change it to "on click".
How? I can't help you with that yet. My javascript isn't that good.

Knockout Input ReadOnly State

I am trying to add a simple functionality in my program and Im having a little trouble figuring out how to do something I wanted.
Here's what I got:
My input textbox, with a link beside it to disable/enable readonly property on that input textbox.
<div>
<input type="text" data-bind="attr: { 'readonly': getreadonlyState() }" value="420" />
Edit
</div>
Here's my knockout script for it:
var ViewModel = function() {
var self = this;
self.getreadonlyState = ko.observable('readonly');
self.readonly = function() {
if (self.getreadonlyState()) {
self.getreadonlyState(undefined);
}
else self.getreadonlyState('readonly');
}
}
ko.applyBindings(new ViewModel());
This works great, but what I wanted is when I click the edit link, it will change the text of the link to something like: "Stop Editing" so when I click "Stop Editing" the readonly property is enabled again.
Here's a fiddle of what Im working on.
Any help will be greatly appreciated, thank you!
Here's an alternative to #thangcao's answer. I'm not saying this is any better or worse, simply an alternative which uses a subscribe handler instead of a computedObservable.
<div>
<input type="text" data-bind="attr: { 'readonly': getreadonlyState() }" value="420" />
</div>
var ViewModel = function() {
var self = this;
self.getreadonlyState = ko.observable('readonly');
self.getreadonlyState.subscribe(function(val) {
self.linkText(val === "readonly" ? "Edit" : "Stop editing");
});
self.readonly = function() {
if (self.getreadonlyState()) {
self.getreadonlyState(undefined);
}
else self.getreadonlyState('readonly');
}
self.linkText = ko.observable("Edit");
}
ko.applyBindings(new ViewModel());
Notice that there's no need for the additional <span> in #thangcao's answer.
Also, why is the "edit"/"stop editing" element an anchor tag? Why not just make it a <span> and do away with the need for the additional inline JavaScript (which you can anyway replace with a return false; inside the readonly function).
http://jsfiddle.net/ajameson/eeTjS/87/
I have updated your Fiddle and hope that it meets your need:
<div>
<input type="text" data-bind="attr: { 'readonly': getreadonlyState() }" value="420" />
<span data-bind="text:linkText"></span>
</div>
var ViewModel = function() {
var self = this;
self.getreadonlyState = ko.observable('readonly');
self.readonly = function() {
if (self.getreadonlyState()) {
self.getreadonlyState(undefined);
}
else {
self.getreadonlyState('readonly');
}
}
self.linkText = ko.computed(function(){
return self.getreadonlyState() == 'readonly' ? "Stopping edit" : "Edit";
}, self);
}
ko.applyBindings(new ViewModel());
You can use this binginHandlers :
ko.bindingHandlers.readOnly = {
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
element.setAttribute("disabled", true);
} else {
element.removeAttribute("disabled");
}
}
};
In my html :
<input type="text" id="create-finess" class="form-control" data-bind="readOnly: _locked" />
Finaly in my JS :
//Constructor of my view model
function ViewModel(resx) {
this._locked = ko.observable();
}
// on init of the page i lock the input
this._load = function () {
this._locked(true);
}

Categories