Adding JavaScript onkeypress to ASP.NET TextBox

I am trying to create a custom UserControl for displaying and editing US phone numbers.  On the editing side, I want to enforce numeric-only data entry in the TextBoxes by using JavaScript and the "onkeypress" event.

The layout of the custom user control is displayed provided in the code box.

I am attempting to add the "onkeypress" event to the three TextBoxes by using the OnLoad event and adding attributes as follows:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Add attributes to the textboxes
        Me.txtAreaCode.Attributes.Add("onkeypress", "javascript: DigitsOnly(e);")
        Me.txtExchange.Attributes.Add("onkeypress", "javascript: DigitsOnly(e);")
        Me.txtNumber.Attributes.Add("onkeypress", "javascript: DigitsOnly(e);")
    End Sub

Nothing seems to be working.  I am very unfamiliar with JavaScript -- perhaps that's my problem?


<%@ Control Language="VB" AutoEventWireup="false" CodeFile="FieldPhone.ascx.vb" Inherits="sections_users_Field_Phone" %>

<script type="text/javascript">
    <![CDATA[
    function DigitsOnly(e)
    {
        if(((e.keyCode >= 48) && (e.keyCode <= 57)) || ((e.keyCode >= 96) && (e.keyCode <= 105)))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    //]]>
</script>

<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0" >
    <asp:View ID="ModeView" runat="server">
        <asp:Label ID="lblPhoneView" runat="server" Text=""></asp:Label>
    </asp:View>
    <asp:View ID="ModeEdit" runat="server">
        <asp:TextBox ID="txtAreaCode" runat="server" MaxLength="3"></asp:TextBox>
        <asp:TextBox ID="txtExchange" runat="server" MaxLength="3"></asp:TextBox>
        <asp:TextBox ID="txtNumber" runat="server" MaxLength="4"></asp:TextBox>
    </asp:View>
</asp:MultiView>

Open in new window

ewolsingAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

codingbeaverCommented:
Change it to:
Me.txtAreaCode.Attributes.Add("onkeypress", "DigitsOnly(e);")

Open in new window

0
leakim971PluritechnicianCommented:
Hello ewolsing,

Try to see if you get alert box :


<%@ Control Language="VB" AutoEventWireup="false" CodeFile="FieldPhone.ascx.vb" Inherits="sections_users_Field_Phone" %>

<script type="text/javascript">
    <![CDATA[
    function DigitsOnly(e)
    {
        if(((e.keyCode >= 48) && (e.keyCode <= 57)) || ((e.keyCode >= 96) && (e.keyCode <= 105)))
        {
            alert("good key !");
        }
        else
        {
            alert("bad key :(");
        }
    }
    //]]>
</script>

<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0" >
    <asp:View ID="ModeView" runat="server">
        <asp:Label ID="lblPhoneView" runat="server" Text=""></asp:Label>
    </asp:View>
    <asp:View ID="ModeEdit" runat="server">
        <asp:TextBox ID="txtAreaCode" runat="server" MaxLength="3"></asp:TextBox>
        <asp:TextBox ID="txtExchange" runat="server" MaxLength="3"></asp:TextBox>
        <asp:TextBox ID="txtNumber" runat="server" MaxLength="4"></asp:TextBox>
    </asp:View>
</asp:MultiView>

Open in new window

0
codingbeaverCommented:
Or, change your HTML code as this.
<asp:TextBox ID="txtAreaCode" runat="server" MaxLength="3" onkeypress="DigitsOnly(event);"></asp:TextBox> 
<asp:TextBox ID="txtExchange" runat="server" MaxLength="3" onkeypress="DigitsOnly(event);"></asp:TextBox> 
<asp:TextBox ID="txtNumber" runat="server" MaxLength="4" onkeypress="DigitsOnly(event);"></asp:TextBox>

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

experts1Commented:
ewolsing,

Please try modification as below!

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="FieldPhone.ascx.vb" Inherits="sections_users_Field_Phone" %> 
 
<script type="text/javascript"> 
    <![CDATA[ 
    function DigitsOnly(e) 
    { 
  if (e.which) {
    var chk = e.which;
    if (((chk >= 48) && (chk <= 57)) || ((chk >= 96) && (chk <= 105)))
          return true;
      return false;
       }

  if (e.keyCode) {
    var chk = e.keyCode;
    if (chk != 08 && chk !=46 && (chk < 48 || chk > 57))
          return true;
      return false;
       }
    } 
    //]]> 
</script> 
 
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0" > 
    <asp:View ID="ModeView" runat="server"> 
        <asp:Label ID="lblPhoneView" runat="server" Text=""></asp:Label> 
    </asp:View> 
    <asp:View ID="ModeEdit" runat="server"> 
        <asp:TextBox ID="txtAreaCode" runat="server" MaxLength="3"></asp:TextBox> 
        <asp:TextBox ID="txtExchange" runat="server" MaxLength="3"></asp:TextBox> 
        <asp:TextBox ID="txtNumber" runat="server" MaxLength="4"></asp:TextBox> 
    </asp:View> 
</asp:MultiView>

Open in new window

0
ewolsingAuthor Commented:
Ok.  I've tried each of the solutions posted so far, and with no success.

codingbeaver:  I tried both methods of accessing the javascript from the textbox -- in the code-behind OnLoad subroutine, and alternatively hard-coded into the textbox declaration on the UserControl.  No success.

experts1: I tried your alternate javascript code, but to no avail.

leakim971:  I replaced the returns with the alerts you suggested.  It's probably telling that I did not get ANY alert window when I tested the UserControl.  That leads me to believe that I still have not yet wired the javascript to the textbox properly.

To all:  I am using Google Chome for my testing, and, to reiterate, this code is placed within a UserControl *.ascx file.  I don't think that would make a difference, but I could be wrong about that.
0
leakim971PluritechnicianCommented:
Could you do a simple form with your control, open the page and paste here page source (right click on the generated page)
We will see what happen
0
leakim971PluritechnicianCommented:
with your controlS (asp:TextBox)
0
ewolsingAuthor Commented:
leakim971:  Sure thing!  Please see the code window for the source generated when I executed a test page containing my UserControl.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
	Untitled Page
</title></head>
<body>
    <form name="form1" method="post" action="FieldPhoneTest.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTgzODI0MDY2N2QYAQUWRmllbGRQaG9uZTEkTXVsdGlWaWV3MQ8PZAIBZLk1Z4czHP4t5xxY/VEbmKvip/Ib" />
</div>

<div>

	<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBALEpJeRCgKV9L+9AwKFjdr5DwKiyuqCDnMUiRZ23bL+purAURx2+5cDzTmf" />

</div>
    <div>
        

<script type="text/javascript">
    <![CDATA[
    function DigitsOnly(e)
    {
        if(((e.keyCode >= 48) && (e.keyCode <= 57)) || ((e.keyCode >= 96) && (e.keyCode <= 105)))
        {
            alert("Good key!");
        }
        else
        {
            alert("Bad key!");
        }
    }
    //]]>
</script>


        <input name="FieldPhone1$txtAreaCode" type="text" maxlength="3" id="FieldPhone1_txtAreaCode" onkeypress="DigitsOnly(event)" />
        <input name="FieldPhone1$txtExchange" type="text" maxlength="3" id="FieldPhone1_txtExchange" onkeypress="DigitsOnly(event)" />
        <input name="FieldPhone1$txtNumber" type="text" maxlength="4" id="FieldPhone1_txtNumber" onkeypress="DigitsOnly(event)" />
    

    </div>
    </form>

</body>
</html>

Open in new window

0
leakim971PluritechnicianCommented:
Remove this tags:

    <![CDATA[

and :

    //]]>
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ewolsingAuthor Commented:
leakim971:  Thanks!  Now the script is now executing.

However, no matter what key is pressed (alpha or numeric), the alert block is returning "Good key!"  Why is the script not branching as it should?  I think it may have something to do with my inexperience with JavaScript

I retried the script that 'experts1' suggested, but with similar results in that it permitted both alpha and numeric characters to pass.

The whole point of this exercise is to permit only numeric characters into the TextBoxes.
0
vb_studentCommented:
another test would be to put the java comand "alert('event fired')"  into the onkeypress event to see if it is firing at all.

E.G

<asp:TextBox ID="txtAreaCode" runat="server" MaxLength="3" onheypress="alert('event fired')" > </asp:TextBox>


then if this fires look and see what value E is passing on. perhaps it is sending an incompatible value and it is ignoring the events.

hope this helps.
0
leakim971PluritechnicianCommented:
only numeric : 0x30 to 0x39


if( (e.keyCode >= 48) && (e.keyCode <= 57) )

Open in new window

0
leakim971PluritechnicianCommented:
So :


function DigitsOnly(e)
    {
        if( (e.keyCode >= 48) && (e.keyCode <= 57) )
        {
            alert("Good key!");
        }
        else
        {
            alert("Bad key!");
        }
    }

Open in new window

0
vb_studentCommented:
i just saw the last comment. perhaps you can check that e value as i mentioned. you could do this by running the alert like this.   alert(e.keycode)
0
ewolsingAuthor Commented:
Below is how the problem was finally solved.  To inhibit the addition of an undesired character, I had to assign the returnValue of the event (e.returnValue=false) instead of simply "return false;".

Thanks again!

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="FieldPhone.ascx.vb" Inherits="sections_users_Field_Phone" %>

<script type="text/javascript">
    function DigitsOnly(e)
    {
        if ((e.keyCode >= 48) && (e.keyCode <= 57)) {
            e.returnValue=true;
        } else {
            e.returnValue=false;
        }
    }
</script>


   
       
   
   
       
       
       
   
0
leakim971PluritechnicianCommented:
You're welcome! Thanks for the points and for sharing the final code! Happy new year!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.