I have created my own code to provide date masking and validation for TextBox control in asp.net. Below is the code. The code works perfectly.
function IsValidDate(ctrlID)
{
var validDate=true;
var myT=document.getElementById("ctl00_ContentPlaceHolder1_CandidateResume1_TabContainer1_TabPanel2_Education1_"+ctrlID);
var mm=myT.value.substring(0,2);
var dd=myT.value.substring(5,3);
var yy=myT.value.substring(6);
if(mm!=0 && mm>12){
myT.value=""; validDate=false;
}
else
{
if((yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0)
{
if(mm==2 && dd>29){
myT.value=""; validDate=false;
}
}
else
{
if(mm==2 && dd>28){
myT.value=""; validDate=false;
}
else
{
if(dd!=0 && dd>31){
myT.value=""; validDate=false;
}
else
{
if((mm==4 || mm==6 || mm==9 || mm==11) && (dd!=0 && dd>30)){
myT.value=""; validDate=false;
}
}
}
}
}
if(validDate==false)
{
myT.style.backgroundColor='#FF0000';
myT.focus;
}
else
myT.style.backgroundColor='#FFFFFF';
}
function maskDate(ctrlID)
{
var myT=document.getElementById("ctl00_ContentPlaceHolder1_CandidateResume1_TabContainer1_TabPanel2_Education1_"+ctrlID);
var KeyID = (window.event) ? window.event.keyCode : 0;
if((KeyID>=48 && KeyID<=57) || KeyID==8)
{
if(KeyID==8)
return;
if(myT.value.length==2)
{
myT.value=myT.value+"/";
}
if(myT.value.length==5)
{
myT.value=myT.value+"/";
}
}
else
{
window.event.keyCode=0;
}
}
The problem -
I am attaching these functions to the textbox as -
TextBox1.Attributes.Add("onFocusout","IsValidDate('TextBox1');");
TextBox1.Attributes.Add("onKeyPress","maskDate('TextBox1');");
If you look at the javascript code I have collected the control id in myT variable. I have also passed the id of textbox while attaching the js functions using Attributes.Add()
My problem is that i dont want to pass the id of the textbox as i am already attaching it. That is i want to write the code as
TextBox1.Attributes.Add("onFocusout","IsValidDate();");
TextBox1.Attributes.Add("onKeyPress","maskDate();");
My question is how can i get the id of textbox to which i have attached these functions witin JS code.
NOTE: I DONT WANT TO PASS CONTROL NAME OR CONTROLS CLIENTID WHILE ADDING ATTRIBUTES. PLEASE NOTE THAT I WANT TO REPLACE
TextBox1.Attributes.Add("onFocusout","IsValidDate('TextBox1');");
WITH
TextBox1.Attributes.Add("onFocusout","IsValidDate();");
I WANT TO ATTACH THESE FUNCTIONS WITH MULTIPLE TEXTBOXES.
AS I AM USING .Attributes.Add(...) I WANT TO GET THE SAME CONTROLS CLIENTID WITHIN JS CODE.
Your help is highly appreciated.
Thanks and Regards
Mohammad Irfan
var txtControl = document.getElementById("<%= txtControl.ClientID %>");
Control.ClientID
Either pass TextBox1.ClientID to the function, or change the function call to be IsValidDate(this.id). But as you don't want to pass these in, you can place the TextBox1.ClientID in your javascript or use jquery to find it using $('[id*=TextBox1]').
Related
I need to hide few fields in a Quick View Form based on an Option Set (Choice) selection in that Quick View form. However it is not working, so am sharing the code I used for the same here. In my code, I am trying to hide certain fields if the option selected is not equal to a particular value...
function hideFields(executionContext) {
var formContext = executionContext.getFormContext();
var quickViewControl = formContext.ui.quickForms.get("General");
if (quickViewControl != undefined) {
if (quickViewControl.isLoaded()) {
var orgtypevalue = quickViewControl.getControl("new_organizationtype").getValue();
if (orgtypevalue != 248870006) {
quickViewControl.getControl("new_recipienttype").setVisible(false);
quickViewControl.getControl("new_businesstype").setVisible(false);
quickViewControl.getControl("new_businesstypecode").setVisible(false);
quickViewControl.getControl("new_businesstypecharacteristicstypecode").setVisible(false);
return;
}
else {
// Wait for some time and check again
setTimeout(getAttributeValue, 10, executionContext);
}
}
else {
console.log("No data to display in the quick view control.");
return;
}
else {
quickViewControl.getControl("new_recipienttype").setVisible(true);
quickViewControl.getControl("new_businesstype").setVisible(true);
quickViewControl.getControl("new_businesstypecode").setVisible(true);
quickViewControl.getControl("new_businesstypecharacteristicstypecode").setVisible(true);
return;
}
}
}
I need to know where am I wrong. Any help will be appreciated.
Thanks!
you need to update the following
first if version 9 I am updating this
"var quickViewControl = formContext.ui.quickForms.get("General");"
to "var quickViewControl = formContext._ui._quickForms.get("General");"
&
"var orgtypevalue = quickViewControl.getControl("new_organizationtype").getValue();"
to
"var orgtypevalue = quickViewControl.getAttribute("new_organizationtype").getValue();"
& update else with message to wait and call the function again like this
"setTimeout(hideFields, 10, executionContext);"
and add else for the If of "quickViewControl != undefined"
Kindly find the updated code:
function hideFields(executionContext) {
var formContext = executionContext.getFormContext();
var quickViewControl = formContext._ui._quickForms.get("General");
if (quickViewControl != undefined) {
if (quickViewControl.isLoaded()) {
var orgtypevalue = quickViewControl.getAttribute("new_organizationtype").getValue();
if (orgtypevalue != 248870006) {
quickViewControl.getControl("new_recipienttype").setVisible(false);
quickViewControl.getControl("new_businesstype").setVisible(false);
quickViewControl.getControl("new_businesstypecode").setVisible(false);
quickViewControl.getControl("new_businesstypecharacteristicstypecode").setVisible(false);
return;
}
else {
// Wait for some time and check again
setTimeout(hideFields, 10, executionContext);
}
}
else {
//console.log("No data to display in the quick view control.");
//return;
setTimeout(hideFields, 10, executionContext);
}
}
}
I have four controls in a page with update panel. Initially mouse focus is set to first control. When I partially post back the page to server the focus automatically moves to first control from the last focused control from the control I have tabbed down to. Is there any way to maintain the last focus?
Take a look at Restoring Lost Focus in the Update Panel with Auto Post-Back Controls:
The basic idea behind the solution is to save the ID of the control
with input focus before the update panel is updated and set input
focus back to that control after the update panel is updated.
I come with the following JavaScript which restores the lost focus in
the update panel.
var lastFocusedControlId = "";
function focusHandler(e) {
document.activeElement = e.originalTarget;
}
function appInit() {
if (typeof(window.addEventListener) !== "undefined") {
window.addEventListener("focus", focusHandler, true);
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}
function pageLoadingHandler(sender, args) {
lastFocusedControlId = typeof(document.activeElement) === "undefined"
? "" : document.activeElement.id;
}
function focusControl(targetControl) {
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var focusTarget = targetControl;
if (focusTarget && (typeof(focusTarget.contentEditable) !== "undefined")) {
oldContentEditableSetting = focusTarget.contentEditable;
focusTarget.contentEditable = false;
}
else {
focusTarget = null;
}
targetControl.focus();
if (focusTarget) {
focusTarget.contentEditable = oldContentEditableSetting;
}
}
else {
targetControl.focus();
}
}
function pageLoadedHandler(sender, args) {
if (typeof(lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
var newFocused = $get(lastFocusedControlId);
if (newFocused) {
focusControl(newFocused);
}
}
}
Sys.Application.add_init(appInit);
I find this more elegant:
(function(){
var focusElement;
function restoreFocus(){
if(focusElement){
if(focusElement.id){
$('#'+focusElement.id).focus();
} else {
$(focusElement).focus();
}
}
}
$(document).ready(function () {
$(document).on('focusin', function(objectData){
focusElement = objectData.currentTarget.activeElement;
});
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(restoreFocus);
});
})();
I know how to enable/disable individual validator controls on the client side using
ValidatorEnable(validator, false);
But how do you enable/disable all the validators within a ValidationGroup?
The validator properties aren't rendered as attributes unfortunately, so I don't know a good way to select them directly. You can try to iterate the Page_Validators array and filter out the ones you want to work with.
Try:
$.each(Page_Validators, function (index, validator){
if (validator.validationGroup == "your group here"){
ValidatorEnable(validator, false);
}
});
Check this blogpost explaining how with javascript. The main part of the code from the blog:
<script type="text/javascript">
function HasPageValidators()
{
var hasValidators = false;
try
{
if (Page_Validators.length > 0)
{
hasValidators = true;
}
}
catch (error)
{
}
return hasValidators;
}
function ValidationGroupEnable(validationGroupName, isEnable)
{
if (HasPageValidators())
{
for(i=0; i < Page_Validators.length; i++)
{
if (Page_Validators[i].validationGroup == validationGroupName)
{
ValidatorEnable(Page_Validators[i], isEnable);
}
}
}
}
</script>
Alternatively you can simply have ValidationGroup attribute with each validator defined .
Then you wont need any Jquery or javascript stuff to close them.
Here is the link that worked for me.
http://www.w3schools.com/aspnet/showasp.asp?filename=demo_prop_webcontrol_imagebutton_validationgroup
I have an ASP.NET code-behind page linking several checkboxes to JavaScript methods. I want to make only one JavaScript method to handle them all since they are the same logic, how would I do this?
Code behind page load:
checkBoxShowPrices.Attributes.Add("onclick", "return checkBoxShowPrices_click(event);");
checkBoxShowInventory.Attributes.Add("onclick", "return checkBoxShowInventory_click(event);");
ASPX page JavaScript; obviously they all do the same thing for their assigned checkbox, but I'm thinking this can be reduced to one method:
function checkBoxShowPrices_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%=checkBoxShowPrices.UniqueID%
>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
}
}
function checkBoxShowInventory_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%
=checkBoxShowInventory.UniqueID%>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
}
}
Add to the event the checkbox that is raising it:
checkBoxShoPrices.Attributes.Add("onclick", "return checkBox_click(this, event);");
Afterwards in the function you declare it like this:
function checkBoxShowPrices_click(checkbox, e){ ...}
and you have in checkbox the instance you need
You can always write a function that returns a function:
function genF(x, y) {
return function(z) { return x+y*z; };
};
var f1 = genF(1,2);
var f2 = genF(2,3);
f1(5);
f2(5);
That might help in your case, I think. (Your code-paste is hard to read..)
The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially).
Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a <textarea> control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line.
For more information on the bug, read it here.
This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0.
Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.
I use this function adapted from codesta. [Edit: the very same one, I see, that scares you! Oops. Can't help you then.]
http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html.
You use it by surrounding your code with a div like so. You could subclass the Form to include this automatically. I don't use it that much, so I didn't.
<div onkeypress="return FireDefaultButton(event, '<%= aspButtonID.ClientID %>')">
(your form goes here)
</div>
Here's the function.
function FireDefaultButton(event, target)
{
// srcElement is for IE
var element = event.target || event.srcElement;
if (13 == event.keyCode && !(element && "textarea" == element.tagName.toLowerCase()))
{
var defaultButton;
defaultButton = document.getElementById(target);
if (defaultButton && "undefined" != typeof defaultButton.click)
{
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation)
event.stopPropagation();
return false;
}
}
return true;
}
It seems that the fix codesta.com that harpo link to is no longer necessary, since the fix event.srcElement is not integrade in ASP.NET 3.5. The implementation of DefaultButton does however still have some problems, because it is catching the Enter key press in too many cases. For example: If you have activated a button in the form using tab, pressing Enter should click on the button and not submit the form.
Include the following JavaScript code at the bottom of your ASP.NET web page to make Enter behave the way it should.
// Fixes ASP.NET's behavior of default button by testing for more controls
// than just textarea where the event should not be caugt by the DefaultButton
// action. This method has to override ASP.NET's WebForm_FireDefaultButton, so
// it has to included at the bottom of the page.
function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (!(
src
&&
(
src.tagName.toLowerCase() == "textarea"
|| src.tagName.toLowerCase() == "a"
||
(
src.tagName.toLowerCase() == "input"
&&
(
src.getAttribute("type").toLowerCase() == "submit"
|| src.getAttribute("type").toLowerCase() == "button"
|| src.getAttribute("type").toLowerCase() == "reset"
)
)
|| src.tagName.toLowerCase() == "option"
|| src.tagName.toLowerCase() == "select"
)
)) {
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton && typeof (defaultButton.click) != "undefined") {
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
}
return true;
}
For this particular issue, the reason is because javascript generated by
ASP.NET 2.0 has some IE only notation: event.srcElement is not availabe in
FireFox (use event.target instead):
function WebForm_FireDefaultButton(event, target) {
if (!__defaultFired && event.keyCode == 13 && !(event.srcElement &&
(event.srcElement.tagName.toLowerCase() == "textarea"))) {
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton && typeof(defaultButton.click) !=
"undefined") {
__defaultFired = true;
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
return true;
}
If we change the first 2 lines into:
function WebForm_FireDefaultButton(event, target) {
var element = event.target || event.srcElement;
if (!__defaultFired && event.keyCode == 13 && !(element &&
(element.tagName.toLowerCase() == "textarea"))) {
Put the changed code in a file and then do
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptInclude("js1", "JScript.js");
}
Then it will work for both IE and FireFox.
Source:
http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html