473,725 Members | 2,295 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I control textbox input for every keypress in ASP.NET

Are there any javascript codes there?
>

Answer: Yes

On the PageLoad event call InitialClientCo ntrosl as follows

/// <summary>
/// This will add client-side event handlers for most of the
form controls so
/// that proper behaviors will happend ( uppercase entry,
running total,etc.).
/// This will also register the call to client script to compute
the total.
/// </summary>
private void InitializeClien tControlsHandle rs()
{
txbName.Attribu tes.Add("onkeyp ress", "return
InputUpperCaseO nly(event)" );

txbExpiryDateMM .Attributes.Add ("onkeypress ", "return
InputNumberOnly (event)" );
txbExpiryDateMM .Attributes.Add ("onfocusout ",
"TwoDigits(this )" );
txbExpiryDateMM .Attributes.Add ("onkeyup",
"JumpIfFilledUp (event, this,
document.getEle mentById('txbEx piryDateYY'), 2 )" );

txbExpiryDateYY .Attributes.Add ("onkeypress ", "return
InputNumberOnly (event)" );
txbExpiryDateYY .Attributes.Add ("onfocusout ",
"TwoDigits( this)" );
txbExpiryDateYY .Attributes.Add ("onkeyup",
"JumpIfFilledUp ( event, this, document.getEle mentById('txbOr der00'),
2 )" );

txbCardNumber.A ttributes.Add(" onkeypress", "return
InputNumberOnly (event)" );

foreach(TextBox ctrl in amountControls)
{
ctrl.Attributes .Add("onkeyup", "getTotalAmount ()");
ctrl.Attributes .Add("onchange" ,"getTotalAmoun t()");
ctrl.Attributes .Add("onkeypres s","return
InputNumberOnly (event)");
}

foreach(TextBox ctrl in orderControls)
{
ctrl.Attributes .Add("onkeypres s","return
InputUpperCaseN oSpaceOnly(even t)");
}

rbtnCredit.Attr ibutes.Add("onc lick", @"if (! confirm('You
have selected a CREDIT RETURN transaction.\r\ n \r\n Press OK BUTTON
if this correct.') )
document.getEle mentById('rbtnA uthorize').clic k();");

Page.RegisterCl ientScriptBlock ("getTotalAmoun t",
CommonUtil.Encl osedJavascript(
" function getTotalAmount( ) "
," { "
," var t = 0.0; "
," var i = 0; "
," for (i = 0; i < " + MAX_ITEMS + " ; i++) "
," { "
," var sf = \"txbAmount\ " + formatNumber(i,
\"00\");"
," var t1 = document.getEle mentById( sf); "
," if ( t1 != null ) "
," { var v1 = t1.value; "
," var val = parseFloat(v1); "
," if ( !isNaN( val ) ) t += val; "
," } "
," } "
," d = document.getEle mentById(\"tota l\"); "
," d.innerHTML = \"Total Amount :&nbsp;&nbsp; \" +
formatNumber(t, \"$#,##0.00\ "); "
," } "
," function TwoDigits(x) "
," { if (x.value.length 0 ) {"
," var y = '0' + x.value;"
," x.value = y.substr( y.length-2) ; "
,"} }"

));

Page.RegisterSt artupScript("Pr eComputeTotal",
"<script>getTot alAmount();" +
"document.getEl ementById( \"" + txbName.ClientI D +
"\").focus( ); " +
"document.getEl ementById( \"" + txbName.ClientI D +
"\").select ();</script>");
}

hre are some js script used
// Original JavaScript code by Duncan Crombie: dc******@chirp. com.au

// CONSTANTS
var separator = ","; // use comma as 000's separator
var decpoint = "."; // use period as decimal point
var percent = "%";
var currency = "$"; // use dollar sign for currency

function formatNumber(nu mber, format, print) { // use:
formatNumber(nu mber, "format")
if (print) document.write( "formatNumb er(" + number + ", \"" +
format + "\")<br>");

if (number - 0 != number) return null; // if number is NaN
return null
var useSeparator = format.indexOf( separator) != -1; // use
separators in number
var usePercent = format.indexOf( percent) != -1; // convert
output to percentage
var useCurrency = format.indexOf( currency) != -1; // use
currency format
var isNegative = (number < 0);
number = Math.abs (number);
if (usePercent) number *= 100;
format = strip(format, separator + percent + currency); //
remove key characters
number = "" + number; // convert number input to string

// split input value into LHS and RHS using decpoint as divider
var dec = number.indexOf( decpoint) != -1;
var nleftEnd = (dec) ? number.substrin g(0, number.indexOf( ".")) :
number;
var nrightEnd = (dec) ? number.substrin g(number.indexO f(".") +
1) : "";

// split format string into LHS and RHS using decpoint as
divider
dec = format.indexOf( decpoint) != -1;
var sleftEnd = (dec) ? format.substrin g(0, format.indexOf( ".")) :
format;
var srightEnd = (dec) ? format.substrin g(format.indexO f(".") +
1) : "";

// adjust decimal places by cropping or adding zeros to LHS of
number
if (srightEnd.leng th < nrightEnd.lengt h) {
var nextChar = nrightEnd.charA t(srightEnd.len gth) - 0;
nrightEnd = nrightEnd.subst ring(0, srightEnd.lengt h);
if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1); //
round up

// patch provided by Patti Marcoux 1999/08/06
while (srightEnd.leng th nrightEnd.lengt h) {
nrightEnd = "0" + nrightEnd;
}

if (srightEnd.leng th < nrightEnd.lengt h) {
nrightEnd = nrightEnd.subst ring(1);
nleftEnd = (nleftEnd - 0) + 1;
}
} else {
for (var i=nrightEnd.len gth; srightEnd.lengt h >
nrightEnd.lengt h; i++) {
if (srightEnd.char At(i) == "0") nrightEnd += "0"; // append
zero to RHS of number
else break;
}
}

// adjust leading zeros
sleftEnd = strip(sleftEnd, "#"); // remove hashes from LHS of
format
while (sleftEnd.lengt h nleftEnd.length ) {
nleftEnd = "0" + nleftEnd; // prepend zero to LHS of number
}

if (useSeparator) nleftEnd = separate(nleftE nd, separator); //
add separator
var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd :
""); // combine parts
output = ((useCurrency) ? currency : "") + output +
((usePercent) ? percent : "");
if (isNegative) {
// patch suggested by Tom Denn 25/4/2001
output = (useCurrency) ? "(" + output + ")" : "-" + output;
}
return output;
}

function strip(input, chars) { // strip all characters in 'chars'
from input
var output = ""; // initialise output string
for (var i=0; i < input.length; i++)
if (chars.indexOf( input.charAt(i) ) == -1)
output += input.charAt(i) ;
return output;
}

function separate(input, separator) { // format input using
'separator' to mark 000's
input = "" + input;
var output = ""; // initialise output string
for (var i=0; i < input.length; i++) {
if (i != 0 && (input.length - i) % 3 == 0) output += separator;
output += input.charAt(i) ;
}
return output;
}

// input filtering function
// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function letternumber(e)
{
var key;
var keychar;

if (window.event)
key = window.event.ke yCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromChar Code(key);
keychar = keychar.toLower Case();

// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;

// alphas and numbers
else if ((("abcdefghijk lmnopqrstuvwxyz 0123456789").in dexOf(keychar)
-1))
return true;
else
return false;
}

function InputNumberOnly (e)
{
var key;
var keychar;

if (window.event)
key = window.event.ke yCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromChar Code(key);
keychar = keychar.toLower Case();

// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;

// alphas and numbers
else if ((("0123456789. ").indexOf(keyc har) -1))
return true;
else
return false;
}
function InputUpperCaseO nly(e)
{
var key;
var keychar;

if (window.event)
key = window.event.ke yCode;
else if (e)
key = e.which;
else
return true;

keychar = String.fromChar Code(key);
keychar = keychar.toUpper Case();

// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;

if (window.event)
window.event.ke yCode = keychar.charCod eAt(0);
else if (e)
e.which = keychar.charCod eAt(0);

return true;
}

function InputUpperCaseN oSpaceOnly(e)
{
var key;
var keychar;

if (window.event)
key = window.event.ke yCode;
else if (e)
key = e.which;
else
return true;

keychar = String.fromChar Code(key);
keychar = keychar.toUpper Case();

// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;
if (((" ").indexOf(keyc har) -1))
return false;
if (window.event)
window.event.ke yCode = keychar.charCod eAt(0);
else if (e)
e.which = keychar.charCod eAt(0);

return true;
}

function JumpIfFilledUp( e, obj1, obj2, len)
{
var key;
var keychar;

if (window.event)
key = window.event.ke yCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromChar Code(key);
keychar = keychar.toLower Case();

// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
{
return true;
}

// alphas and numbers
// else if ((("0123456789. ").indexOf(keyc har) -1))
//{
else if ( obj1.value.leng th == len )
{
obj2.focus();
obj2.select();

}

return true;
//}
//else
// return false;


}

Feb 13 '07 #1
0 11992

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2163
by: RTM | last post by:
Can anyone help me with the following issue? I've seen some similar questions here, but none relating to a textbox control.... I have a form with several controls, one of them being a textbox control with AutoPostBack set to true. I need to fire a method ONLY when the form has posted back due to a button click (no problem here), or from the user typing text in the text box and hitting enter. I can't call this method from any postback,...
2
3626
by: John Lau | last post by:
Hi, Is there documentation that talks about the page lifecycle, the lifecycle of controls on the page, and the rendering of inline code, in a single document? Thanks, John
6
2818
by: Tim Westmoreland | last post by:
Can someone tell me how to raise an event or trap when the maxlength of a server side textbox has been reached?
4
4528
by: Tom | last post by:
I have a VB.NET user control that I wrote - this control has three or four other controls on it (textbox, combobox, datetime picker, etc). Now, whenever the control is on a form and the user enters anything into the textbox (for instance) I trap the keypress event to handle some stuff (i.e. if it is an enter key, etc). Now, once I am done with handling the keypress event for the textbox, I then need to pass that keypress event BACK to the...
2
15458
by: bretth | last post by:
In a VB.Net Windows Forms application, I have a user control that handles mouse events. Another section of code programmatically adds a label to the control. I would like label to ignore all events allowing the user control to react to the mouse click. Setting the Enabled property on the label to False comes close, but I don't want the font color to change. Does anyone have an idea how .NET implements the code behind the Enabled...
3
2130
by: windy | last post by:
I got a question about keypress event on textbox: I found that the keypress event doesn't invoked when i press the "." button on alphabetic keyboard, however if i use numberpad's "." button keypress event is invoked. Any idea and solutions? Thanks.
3
2854
by: =?Utf-8?B?Q2hyaXM=?= | last post by:
I have VS 2005 (C#) There is a control numericUpDown so you can spin numeric values. What I need to do is to spin date (+- one day). How to do that? Moreover, I want a user to type the date as well. So the control should validate the typed values on the fly. Is it possible?
3
2892
by: =?Utf-8?B?QmVybmFyZG8gU2FsYXphciBuZXdi?= | last post by:
Hi everybody... i need help with this issue: i have a textbox control with the focus. at side, i have a datagridview control populated with some data. i need to control behavior of dgv control from textbox. when i press pagedown/pageup key (in textbox), i need to send that key to dgw, to move the data up/down, but, without loss the focus in textbox. i already studied the sendkeys.send, but i dont know how to send a key to control, the...
2
6275
by: Jason Huang | last post by:
Hi, How do I override a TextBox's KeyPress evnt? And how do we use it? Thanks for help. Jason
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.