datepicker and focusout in textbox - c#

i have a datepicker on a textbox and in the same time i'm using a function that checks if the user has entered the right date and time format using javascript.
The problem i am facing is that whenever i have the mouse selected on the textbox the datepicker shows as it should but if i want to select a date from the datepicker the focusout() function is executed and i must re-click again on the date from the datepicker to be selected.
here is my code:
$('#StartDateTime').datepicker({
/* here is only to stay focusin() on the textbox after selecting date */
constrainInput: false,
fixFocusIE: false,
onSelect: function (dateText, inst) {
this.fixFocusIE = true;
$(this).change().focus();
},
onClose: function (dateText, inst) {
this.fixFocusIE = true;
this.focus();
},
beforeShow: function (input, inst) {
var result = $.browser.msie ? !this.fixFocusIE : true;
this.fixFocusIE = false;
return result;
}
}).click(function () { $(this).focus() });
$("#StartDateTime").focusout(function () {
if (sDTValid() == false) {
alert("Please enter Date (Day/Month/Year) & Time (HH:MM AM or PM)");
}
});
function sDTValid() {
/* this is the function of date and time format validation*/
var sDT = document.getElementById('StartDateTime').value;
if (sDT.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4}) (\d{1,2}):(\d{2}) (.*)$/)) {
return true;
}
else {
return false;
}
}

the 'focusout' event will be triggered when user click on the datepicker element because it's not part of the input#StartDateTime
you can use other event when value is changed eg. 'input'
$("#StartDateTime").on('input', function () {
if (sDTValid() == false) {
alert("Please enter Date (Day/Month/Year) & Time (HH:MM AM or PM)");
}
});

Related

Invoke kendo grid create action method to a newly inserted row from javascript

I have an autocomplete and a grid where my intention is to push records from Autocomplete into the grid and save those records using grid's create action from there by invoking a method set in a custom button. Please look at the attached picture to get a clear idea of what my setup looks like.
My saveTerminalRow function doesn't work as expected. Please help.
<div>
#(Html.Kendo().AutoComplete()
.Name("terminalsAutoComplete")
.DataTextField("cmp_name")
// omitted for brevity
.Events(e => e.Select("onTerminalNameSelect"))
)
</div>
<div>
#(Html.Kendo()
.Grid<ProjectName.TerminalOutOfState>()
.Name("manageTOSSqlRecordsGrid")
.Columns(columns =>
{
columns.Bound(c => c.TerminalOutOfStateID).Hidden();
columns.Bound(c => c.TerminalCompanyID).Title("Terminal ID").Width(60);
columns.Bound(c => c.CompanyID).Title("Region").ClientTemplate("#=CompanyName#").Width(40);
columns.Command(cmd =>
{
cmd.Edit();
cmd.Destroy();
cmd.Custom("Save").Visible("showSaveCommand").Click("saveTerminalRow");
}).Title("Action").Width(80);
})
.ToolBar(tbr =>
{
tbr.Create();
tbr.Custom().Text("Load the table");
})
.Editable(edt => edt.Mode(GridEditMode.PopUp).TemplateName("TOoSTemplate").CreateAt(GridInsertRowPosition.Top))
.DataSource(dataSrc => dataSrc
.Ajax()
.ServerOperation(true)
.PageSize(15)
.Model(mdl => mdl.Id(column => column.TerminalOutOfStateID))
.Create(update => update.Action("UpsertTerminalOoSRecordAsync", "Configuration"))
//omitted for brevity
)
.AutoBind(false)
)
</div>
My scripts are like follows:
<script>
//This will add the data from autocomplete into the grid.
function onTerminalNameSelect(e) {
var dataItem = this.dataItem(e.item);
var terminalData = {
TerminalOutOfStateID: 0,
TerminalCompanyID: dataItem.cmp_id,
CompanyID: dataItem.region_id,
CompanyName: dataItem.region_name
};
var grid = $("#manageTOSSqlRecordsGrid").data("kendoGrid");
grid.dataSource.add(terminalData);
}
//This is used to hide and show "Save" button to those rows that are not yet saved to Db.
function showSaveCommand(dataItem) {
// show the Save button for the item with TerminalOutOfStateID =0
if (dataItem.TerminalOutOfStateID == 0) {
return true;
}
else {
return false;
}
}
//This is the method to save the inserted row into Db by calling the create action method. But this doesn't work:
function saveTerminalRow(e) {
var terminalData = this.dataItem($(e.currentTarget).closest("tr"));
var grid = $("#manageTOSSqlRecordsGrid").data("kendoGrid");
grid.saveRow();
}
</script>
Also please advise on how to hide the save button next to unsaved rows after the save operation succeeds.
Well, I can answer my own question now.
This is how I ended up solving this problem:
function saveTerminalRow(e) {
var terminalData = this.dataItem($(e.currentTarget).closest("tr"));
var saveButton = $(e.currentTarget).closest("tr td a.k-grid-Save");
$.ajax({
type: "POST",
url: "#Url.Action("AddTerminalOoSRecordAsync", "Configuration")",
contentType: "application/json",
data: JSON.stringify(terminalData),
success: function (result) {
var title = "", content = "";
if (result[0].TerminalOutOfStateID != undefined && result[0].TerminalOutOfStateID > 0) {
if (!result[0].IsAlreadyInDb) {
title = "Save Success";
content = "New record has been saved.";
}
else {
title = "No new row inserted";
content = "This terminal already exists in Db.";
}
} else {
title = "Save Failed";
content = "Record is not saved.";
}
$("<div></div>").kendoDialog({
closable: false, // hide X
title: title,
content: content,
actions: [{
text: "OK",
action: function (e) {
if (result[0].TerminalOutOfStateID != undefined && result[0].TerminalOutOfStateID > 0) {
saveButton.remove();
}
return true;
},
primary: true
}]
}).data("kendoDialog").open().center();
},
error: function (request, error) {
alert("Record Saving failed.");
}
});
}

ajax calendar control not reset

I have an ajax calendar control used in my form for to date and from date.
The issue with it is, if I select date from previous year and click on reset button, the textbox containing date gets cleared but now when focus is set on the textbox the calendar control shows month of the year previously selected.
Is there any way we can reset calendar control as well on click of the reset button?
function Reset(divs) {
$(".ui-tooltip-content").parents('div').remove();
ClearErrorMsg();
$('#' + divs + ' input[type="text"]').val('');
$('#' + divs + ' select').val('');
$('#' + divs + ' input[type="text"]').attr({ "value": "" });
var BrwsrType = BrowserType();
if (BrwsrType == 'IE') {
$('#' + divs + ' select option').each(function () {
$("select option").removeAttr('selected');
})
};
$("select").each(function (i) {
$('select :nth-child(1)').attr('selected', 'selected')
$('select')[i].options[0].selected = true
});
var txtpagesize = $get('txtPageSize');
if (txtpagesize != null) {
txtpagesize.value = txtpagesize.attributes["defValue"].value;
$('#' + txtpagesize.id).attr({ "value": txtpagesize.attributes["defValue"].value });
}
HideDialog();
try {
Page_ClientValidate('');
}
catch (er) {
}
return false;
}
and the function which is called on reset button is as follows
function ResetForm() {
Reset('Search');
$(".dropdown").each(function () {
$('.dropdown :nth-child(1)').attr('selected', 'selected')
});
isValidDate($get('txtBeginDate'));
isValidDate($get('txtEndDate'));
HideCallOut();
$get('txtBeginDate').defaultValue = "";
$get('txtEndDate').defaultValue = "";
return false;
}
<script type="text/javascript" >
function resetcalendar()
{
$find("_Calendar").set_selectedDate(null);
$("[id*=Calendar]").val("");
$(".ajax__calendar_active").removeClass("ajax__calendar_active");
return false;
}
</script>
where _Calendar is the BehaviorID of Calendarextender and Calendar is the ID of Calendarextender
Hope this helps
Happy Coding

Disable Jquery autocomplete dropdown from codebehind c#

I am using http://jqueryui.com/autocomplete/#combobox for my dropdownlist and it works well.
My problem here is when I disable the dropdown list from code behind it doesn't work.
My code is here.
ASPX
<asp:DropDownList runat="server" CssClass="Dropdown" ID="ddlStatus"> </asp:DropDownList>
JS
function pageLoad() {
/******** Auto Complete *********************/
$(function () {
$("#<%= ddlStatus.ClientID %>").combobox();
});
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function () {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function () {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
//.attr("title", "Show All Items")
//.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
if (value != '') {
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.data("ui-autocomplete").term = "";
} else {
this.input.val("");
this.element.val("");
this.input.data("ui-autocomplete").term = "";
}
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
}
C#
Based some validations I am calling this,
ddlStatus.Enabled = false;
There is an answer here and I am not be to get it work with my code.
Disable jQuery ComboBox when underlying DropDownList is disabled
This is how I have done it. please see the changes enclosed in * *.
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
*select = this.element.hide();*
this._createAutocomplete(*select*);
this._createShowAllButton(*select*);
},
_createAutocomplete: function (*select*) {
var selected = this.element.children(":selected"),
select = this.element.hide(),
value = selected.val() ? selected.text() : "";
*var disabled = select.is(':disabled');*
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.*attr('disabled', disabled)*
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function (*select*) {
var input = this.input,
wasOpen = false;
*var disabled = select.is(':disabled');*
console.log(this.element.attr("id") + " : " + disabled);
$("<a>")
.attr("tabIndex", -1)
*.attr('disabled', disabled)*
//.attr("title", "Show All Items")
//.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
*if ($(this).attr('disabled')) {
return false;
}*
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
if (value != '') {
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.data("ui-autocomplete").term = "";
} else {
this.input.val("");
this.element.val("");
this.input.data("ui-autocomplete").term = "";
}
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);

ReferenceError:event is not defined

In my asp.net mvc3 page, i am using jquery to show a calender to display the events added in the database. Its working fine in google chrome but its showing below error in firefox 19.0.2
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.8.3.js")"> </script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-i.css">
<link rel="stylesheet" href="../../Content/css/styleui.css" />
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Page/dates", null, function (data) {
var s = eval(data);
alert(s);
showevents(s);
});
function showevents(events) {
$("#datepicker").datepicker({
beforeShowDay: function (date) {
var result = [true, '', null];
var matching = $.grep(events, function (event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
result = [true, 'highlight', event.Title];
}
return result;
},
onSelect: function (dateText) {
var date, selectedDate = new Date(dateText), i = 0, event = null;
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
event = events[i];
}
i++;
}
if (event) {
//return [true, "Highlighted", event.Title];
alert(event.Title);
}
}
});
}
});
</script>
<div id="datepicker">
[16:35:16.336] ReferenceError: event is not defined # http://code.jquery.com/jquery-1.8.3.js:579
You are probably missing var event; at the start of showevents function. See comments:
beforeShowDay: function (date) {
var result = [true, '', null];
var matching = $.grep(events, function (event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
// event is not defined
result = [true, 'highlight', event.Title];
}
return result;
},
onSelect: function (dateText) {
var date, selectedDate = new Date(dateText), i = 0, event = null;
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
// event is not defined
event = events[i];
}
i++;
}
if (event) {
//return [true, "Highlighted", event.Title];
// event is not defined
alert(event.Title);
}
}

Adding jquery click event for UpdatePanel

I am using this code for binding asp.net gridview with right click contextmenu using jQuery but every time when I click it (use option in menu list) it reloads the page. What should I do if I want to use an UpdatePanel?
function fnView() {
var lnkView = document.getElementById('<%=lnkView.ClientID %>');
var hiddenField = document.getElementById('<%=fldProductID.ClientID %>');
hiddenField.value = $("div").filter("[type=ContextMenu]")[0].id.replace("Menu", "");
lnkView.click();
}
function fnDelete() {
var lnkDelete = document.getElementById('<%=lnkDelete.ClientID %>');
var hiddenField = document.getElementById('<%=fldProductID.ClientID %>');
hiddenField.value = $("div").filter("[type=ContextMenu]")[0].id.replace("Menu", "");
lnkDelete.click();
}
jQuery.fn.setEvents = function (e) {
var me1 = jQuery(this);
return this.each(function () {
var me = jQuery(this);
me.click(function (e) {
$("div").filter("[type=ContextMenu]").hide();
fnSetMenu(me.children(':first-child').text(), e.pageX, e.pageY);
});
});
};
function fnSetMenu(productID, left, top) {
if ($("#Menu" + productID).html() == null) {
var strMenuHTML = "<div type=\"ContextMenu\" id=\"Menu" + productID + "\" class=\"contextMenuClass\" mouseonmenu=\"1\"><table style='width:100%;'><tr><td onclick=fnView()>View Product</td></tr><tr><td onclick=fnDelete()>Delete Product</td></tr></table></div>";
$("body").append(strMenuHTML);
$.post("MenuHandler.ashx", {}, function (response) {
$("#Menu" + productID).html(response);
});
}
$("#Menu" + productID).css({ top: top + "px", left: left + "px" }).show();
}
$(document).ready(function () {
$("#gvProducts tr.ShowContext").setEvents();
}
);
$(document).click(function (e) {
$clicked = $(e.target);
if (!($clicked.parents().hasClass("ShowContext") || $clicked.hasClass("contextMenuClass") || $clicked.parents().hasClass("contextMenuClass"))) {
$("div").filter("[type=ContextMenu]").hide();
}
});
use jQuery's live function to bind an event inside updatepanel
or
go through this link
http://stackoverflow.com/questions/256195/jquery-document-ready-and-updatepanels

Categories

Resources