How to disable previous dates while using in ajaxToolkit CalendarExtender
One Option is to use a rangevalidator on the textbox the calenderextender is bound to. Ie if you have the TargetID of the calendar extender set to tb1 add a rangeValidator to flag when the contents of tb1 is before today.
Another option is using javascript and here is a good example:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=149 TIP 6.
Here is my full solution to the calendar date restriction problem: What I like about this solution is that you set the MinimumValue and MaximumValue of a RangeValidator and you do not have to modify any javascript. I never found a full solution that did not require recompiling the AjaxControlToolkit.dll. Thanks to http://www.karpach.com/ajaxtoolkit-calendar-extender-tweaks.htm for giving me the idea of how to override key methods in the calendar.js file without having to recompile the AjaxControlToolkit.dll. Also, I got "AjaxControlToolkit is undefined" javascript errors, so I changed those to Sys.Extended.UI. and it works for me when using the 4.0 version of the toolkit.
<%--//ADD THIS NEW STYLE TO STYLESHEET TO GRAY OUT DATES THAT AREN'T SELECTABLE--%>
<style type="text/css">
.ajax__calendar_inactive {color:#dddddd;}
</style>
Either in Page_Load or Init or wherever, set the min and max values for your range validator:
<script runat="server">
protected override void OnLoad(EventArgs e)
{
//set the validator min and max values
this.valDateMustBeWithinMinMaxRange.MinimumValue = DateTime.Today.Date.ToShortDateString();
this.valDateMustBeWithinMinMaxRange.MaximumValue = DateTime.MaxValue.Date.ToShortDateString();
base.OnLoad(e);
}
</script>
Add this javascript somewhere in your page:
<script type="text/javascript">
<%--// ADD DATE RANGE FEATURE JAVASCRIPT TO OVERRIDE CALENDAR.JS--%>
var minDate = new Date('<%= valDateMustBeWithinMinMaxRange.MinimumValue %>');
var maxDate = new Date('<%= valDateMustBeWithinMinMaxRange.MaximumValue %>');
Sys.Extended.UI.CalendarBehavior.prototype._button_onblur_original = Sys.Extended.UI.CalendarBehavior.prototype._button_onblur;
//override the blur event so calendar doesn't close
Sys.Extended.UI.CalendarBehavior.prototype._button_onblur = function (e) {
if (!this._selectedDateChanging) {
this._button_onblur_original(e);
}
}
Sys.Extended.UI.CalendarBehavior.prototype._cell_onclick_original = Sys.Extended.UI.CalendarBehavior.prototype._cell_onclick;
//override the click event
Sys.Extended.UI.CalendarBehavior.prototype._cell_onclick = function (e) {
var selectedDate = e.target.date;
if (selectedDate < minDate || selectedDate > maxDate ) {
//alert('Do nothing. You can\'t choose that date.');
this._selectedDateChanging = false;
return;
}
this._cell_onclick_original(e);
}
Sys.Extended.UI.CalendarBehavior.prototype._getCssClass_original = Sys.Extended.UI.CalendarBehavior.prototype._getCssClass;
Sys.Extended.UI.CalendarBehavior.prototype._getCssClass = function (date, part) {
var selectedDate = date;
if (selectedDate < minDate || selectedDate > maxDate ) {
return "ajax__calendar_inactive";
}
this._getCssClass_original(date, part);
}
</script>
Add this text box to your asp.net page with CalendarExtenter and RangeValidator:
<asp:TextBox ID="textBoxDate" runat="server" />
<ajaxToolkit:CalendarExtender ID="calendarExtender" runat="server" TargetControlID="textBoxDate" />
<asp:RangeValidator ID="valDateMustBeWithinMinMaxRange" runat="server" ControlToValidate="textBoxDate"
ErrorMessage="The date you chose is not in accepted range" Type="Date" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
Using the Ajax toolkit Calendar Extender in the html markup:
<asp:TextBox ID="txtDate" runat="server" CssClass="contentfield" Height="16px" MaxLength="12" width="80px" Wrap="False"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender3" runat="server" Enabled="true" StartDate="<%# DateTime.Now %>" EndDate="<%# DateTime.Now.AddDays(1) %>" Format="dd MMM yyyy" PopupButtonID="imgDatePicker" TargetControlID="txtDate">
</asp:CalendarExtender>
<asp:ImageButton ID="imgDatePicker" runat="Server" AlternateText="Click to show calendar" Height="16px" ImageAlign="Middle" ImageUrl="~/images/Calendar_scheduleHS.png" Width="16px" />
Above you will see that the Calendar only allows one to choose between today or tomorrow by setting
StartDate="<%# DateTime.Now %>"
and
EndDate="<%# DateTime.Now.AddDays(1) %>"
This can also be done in the backend using CalendarExtender1.StartDate = DateTime.Now; or CalendarExtender1.EndDate = DateTime.Now.AddDays(1);
Just add an attribute StartDate="<%# DateTime.Now %>" in you ajaxtoolkit calendarextender control
Following link might help you:
Disable dates in CalendarExtender
Related
I have a ModalPopupExtender tied to a RadListBox so that when an item is selected from the list box, I need a "Please Wait" message while the page behind loads the data into RadCharts. The Modal does Hide when the loading is completed. The problem I'm having is if the same list item is selected again, the Modal popup shows again, but never goes away. I've tried just about everything, but the click/selection of a list item in the RadListBox immediately shows the Modal and I can't seem to find a way to do item checking to see if its the same item, then to do nothing.
Here is my Panel and Modal code (ASPX)
<asp:Panel ID="pnlProgress" runat="server" Height="50px" Width="50px" >
<div>
<div class="popupbody">
<table width="50%">
<tr>
<td align="center">
<asp:Image ID="imgProgress" runat="server" ImageUrl="~/_images/ajax-loader.gif" />
<br />
<br />
<asp:Label ID="lblLoading" runat="server" Text='Please wait...'
Font-Bold="true"></asp:Label>
</td>
</tr>
</table>
</div>
</div>
</asp:Panel>
<ajaxToolKit:ModalPopupExtender ID="mpeProgress" runat="server" TargetControlID="lboxTestedMachines" PopupDragHandleControlID="pnlProgress" `enter code here`
X="1000" Y="500" PopupControlID="pnlProgress" BackgroundCssClass="modalBackground" RepositionMode="RepositionOnWindowResize" BehaviorID="lboxTestedMachines">
</ajaxToolKit:ModalPopupExtender>
And here is my ASPX.CS code
protected void lboxTestedMachines_SelectedIndexChanged(object sender, EventArgs e)
{
int iResultID = Convert.ToInt32(lboxTestedMachines.SelectedValue);
if (tbl_charts.Style.Value != "display:normal")
tbl_charts.Style.Value = "display:normal";
GetMachineName(iResultID);
RdListView_Chart.DataSource = LoadCassetteForFoodChart(iResultID);
GetApprovalRejectionStatus(iResultID);
}
The RadListBox has an internal logic on item click to determine if the item was already selected. If it was, it would not trigger the OnClientSelectedIndexChanging event, hence no postback on clicking a selected item.
The ModalPopupBehavior on the other hand reacts to any click event inside TargetControlID control's element. Here are some code snippets obtained using the browser's DevTools (search for Sys.Extended.UI.ModalPopupBehavior.prototype.initialize by following steps from Get IntelliSense for the client-side object)
initialize: function() {
Sys.Extended.UI.ModalPopupBehavior.callBaseMethod(this, "initialize"),
this._isIE6 = Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version < 7,
this._popupDragHandleControlID && (this._dragHandleElement = $get(this._popupDragHandleControlID)),
this._popupElement = $get(this._popupControlID),
this._createDomElements(),
this._showHandler = Function.createDelegate(this, this._onShow),
$addHandler(this.get_element(), "click", this._showHandler),
this._okControlID && (this._okHandler = Function.createDelegate(this, this._onOk),
$addHandler($get(this._okControlID), "click", this._okHandler)),
this._cancelControlID && (this._cancelHandler = Function.createDelegate(this, this._onCancel),
$addHandler($get(this._cancelControlID), "click", this._cancelHandler)),
this._scrollHandler = Function.createDelegate(this, this._onLayout),
this._resizeHandler = Function.createDelegate(this, this._onLayout),
this.registerPartialUpdateEvents(),
this._resetAnimationsTarget(),
this._onHiding.get_animation() && (this._hidingAnimationEndedHandler = Function.createDelegate(this, function () {
this._isAnimationJustEnded = !0,
this.hide()
}),
this._onHiding.get_animation().add_ended(this._hidingAnimationEndedHandler)),
this._onShowing.get_animation() && (this._showingAnimationEndedHandler = Function.createDelegate(this, function () {
this._isAnimationJustEnded = !0,
this.show()
}),
this._onShowing.get_animation().add_ended(this._showingAnimationEndedHandler))
},
_onShow: function(e) {
if (!this.get_element().disabled)
return this.show(),
e.preventDefault(),
!1
},
Solution 1: Subscribe to the Showing event of the ModalPopupBehavior and allow it to show only when you set a flag from the OnClientSelectedIndexChanging event. The example below stores the flag in the RadListBox client-side object as an expando property:
<telerik:RadCodeBlock runat="server" ID="rdbScripts">
<script type='text/javascript'>
function pageLoadHandler() {
var modalPopupExtenderClientObject = $find("<%= mpeProgress.ClientID %>")
modalPopupExtenderClientObject.add_showing(function (sender, args) {
// "sender" argument represents the Modal popup control client-side object
// sender.get_element() returns the DOM element of the RadListBox
// sender.get_element().control return the client-side object of the RadListBox where we stored the expando property __allowModalPopupShow
if (sender.get_element().control.__allowModalPopupShow !== true) {
args.set_cancel(true);
}
})
}
function OnClientSelectedIndexChanging(sender, args) {
// sender in this context is the RadListBox client-side object
sender.__allowModalPopupShow = true;
}
Sys.Application.add_load(pageLoadHandler);
</script>
</telerik:RadCodeBlock>
Solution 2: Use RadAjaxLoading panel and show it programmatically in OnClientSelectedIndexChanging:
https://docs.telerik.com/devtools/aspnet-ajax/controls/ajaxloadingpanel/how-to/show-and-hide-ajaxloadingpanel-explicitly
https://demos.telerik.com/aspnet-ajax/ajaxloadingpanel/functionality/transparency/defaultcs.aspx
I am using Bootstrap 3 DateTimePicker and I am trying to disable some specific hours in some specific dates. For example, I want to disable 08:00 hour option in 06/27/2018 and 17:00 hour option in 06/30/2018.
I tried to use "disabledHours" option. But this option disables the given hour in all days.
So how can I achieve this?
Here are my codes.
$(".datepicker").datetimepicker({
format: 'MM/DD hh:ii',
datesDisabled: ['2016/08/20'],
autoclose: true,
});
There are no in-built functions to disable specific hours in a specific date. But the case can be achieved by using the onRenderHour method. Store the hours to be disabled in specific dates in the array disabledtimes_mapping. Those will be disabled automatically while rendering the picker.
P.S: This date-picker is deprecated. The same is forked and maintained by AuspeXeu in GitHub.
var disabledtimes_mapping = ["06/27/2018:8", "06/30/2018:17", "06/30/2018:15"];
function formatDate(datestr)
{
var date = new Date(datestr);
var day = date.getDate(); day = day>9?day:"0"+day;
var month = date.getMonth()+1; month = month>9?month:"0"+month;
return month+"/"+day+"/"+date.getFullYear();
}
$(".datepicker").datetimepicker({
format: 'MM/DD hh:ii',
datesDisabled: ['2018-06-20'],
autoclose: true,
onRenderHour:function(date){
if(disabledtimes_mapping.indexOf(formatDate(date)+":"+date.getUTCHours())>-1)
{
return ['disabled'];
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/AuspeXeu/bootstrap-datetimepicker/master/js/bootstrap-datetimepicker.js"></script>
<link href="https://rawgit.com/AuspeXeu/bootstrap-datetimepicker/master/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<input class="datepicker" type="text">
I am new to react and trying to get the actual date and time but I can't figure out how to do so :(
Could someone help me please !
I try to get the date in the initial state and actualise it every second. When I run it, I get a white screen.
import React from 'react';
import './Menubar.css';
import Time from 'react-time';
const Menubar = React.createClass({
getInitialState() {
return {
now: new Date().now(),
};
},
getRealTime: function() {
this.setState(
{
now: new Date().now(),
})
},
/**
* Render the Menubar component
* #return {Component} the App Component rendered
*/
render() {
setInterval(this.getRealTime(), 1000);
return (
<div className="Menubar">
<ul className="Menubar-menu">
<div className="">
<li className="Menubar-name">login name</li>
<li className="Menubar-date"><Time value={this.state.now} format="DD/MM/YYYY" /></li>
<li className="Menubar-time"><Time value={this.state.now} format="HH:mm:ss" /></li>
</div>
</ul>
</div>
);
}
});
export default Menubar;
Two things:
new Date().now() is not a function, new Date() returns the current date and time, so no need to add it.
You try to set the state inside the render function (calling getRealTime every single render, which causes a re-render). As I understand, you want to update the time every second. You could set that up in componentDidMount.
Here's your Menubar component with those things fixed. I also clear the interval when the component unmounts:
const Menubar = React.createClass({
getInitialState() {
return {
now: new Date(),
};
this.interval = null;
},
componentDidMount: function() {
const self = this;
self.interval = setInterval(function() {
self.setState({
now: new Date(),
});
}, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render() {
return (
<div className="Menubar">
<ul className="Menubar-menu">
<div className="">
<li className="Menubar-name">login name</li>
<li className="Menubar-date"><Time value={this.state.now} format="DD/MM/YYYY" /></li>
<li className="Menubar-time"><Time value={this.state.now} format="HH:mm:ss" /></li>
</div>
</ul>
</div>
);
}
});
To just get the current date you can use
var dateVariable = new Date()
dateVariable.getDate()
OR if you want the current Date & Time in full form then,
var dateVariable = Date().toLocaleString()
You can find a comprehensive list of methods available on:
https://hdtuto.com/article/react-js-get-current-date-and-time-example
The above link saved a lot of my time. Hope it works. Happy hacking!
I just want to add to IronmanX46's answer, but it won't let me comment.
I wanted to point out that you can do the exact same thing as
var dateVariable = new Date()
dateVariable.getDate()
var dateVariable = Date().toLocaleString()
by simply doing
var dateVariable = Date()
As per the documentation:
Date()
When called as a function, returns a string representation of the
current date and time. All arguments are ignored. The result is the
same as executing new Date().toString().
There are lots of good websites out there that will give you examples of how to do things, but I find it saves time to just go read the documentation, which usually includes examples. I'll then go check out other examples if I can't understand the documentation.
Date Documentation Link
I try to get date from CalendarExtender in two ways: one with updatepanel and one without but it doesn't work. value of this two calendar extender are null.
It's weird because I can select date from this extenders, and text of textboxes are set to selected date.
How to fix it ?
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="tbPlannedStart"
Format="d">
</asp:CalendarExtender>
<asp:TextBox ID="tbPlannedStart" runat="server"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
<asp:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="tbPlannedEnd"
Format="d">
</asp:CalendarExtender>
<asp:TextBox ID="tbPlannedEnd" runat="server"></asp:TextBox>
protected void btnAddProject_Click(object sender, EventArgs e)
{
var service = new Service1Client("WSHttpBinding_IService13");
var project = new MyProject();
project.PlannedEnd = CalendarExtender2.SelectedDate;
project.PlannedStart = CalendarExtender1.SelectedDate;
service.AddProject(project);
}
It solved my problem:
project.PlannedEnd = System.Convert.ToDateTime(tbPlannedEnd.Text);
project.PlannedStart = System.Convert.ToDateTime(tbPlannedStart.Text);
I'm using MVC2 and have included the Jquery DateTime picker.
For some reason it is not using the default format settings when the pages loads.
The model is passing in a Date and I have set the format to 'dd/mm/yyyy' as I do not want the time to be displayed. The html.editorfor that the datepicker is attached to, shows in the standard 'mm/dd/yyyy hh:mm:ss' format, consequently the validation kicks in with "invalid Date" if the model value if say '15th October 2010', because the standard format complains that there is no "15th" month.
Code from the DatePicker is...
<%= Html.TextBox("", (Model.HasValue ? Model.Value.Date.ToString("dd/mm/yyyy") :
DateTime.Today.ToString("dd/mm/yyyy") ), new { #class = "date" }) %>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#datepicker").datepicker(
{
dateFormat: 'dd/mm/yy',
defaultDate: new Date(),
minDate: new Date()
});
});
</script>
Code calling Datepicker...
<div>
<%=Html.LabelFor(Model => Model.StartDate)%>
<%=Html.EditorFor(Model => Model.StartDate, new { #class = "date" }) %>
<%=Html.ValidationMessageFor(Model => Model.StartDate, "*")%>
</div>
Any ideas?
It seems the problem is actually with the HTML.TextBox rather than the actual JQuery...
This line seems to be the problem,
<%= Html.TextBox("", (Model.HasValue ? Model.Value.Date.ToString("dd/MMM/yyyy") :
DateTime.Today.ToString("dd/MMM/yyyy")), new { #class = "date" })%>
I have broken down the line as follows to check the different elements are working correctly, and they are...
<div><%= Model.HasValue %></div>
<div><%= Model.Value.Date.ToString( "dd/MM/yyyy" ) %></div>
<div><%= DateTime.Today.ToString("dd/MM/yyyy")%></div>
So, simply - this line in a template causes the date formatting to be ignored... any suggestions?
<div><%= Html.TextBox("", Model.Value.Date.ToString("dd/MM/yyyy"))%></div>
Are you setting the ID of the textBox correctly, I can see you have a class "date" but not the id.
you may also need the localization files for the datepicker available at Google
I still can't see in your javascript where the selector:
$("#datepicker")
is associated to your textbox. Shouldn't the selector be
$('.date')
Maybe I'm missing something.