?
Solved

Adding JavaScript onkeypress to ASP.NET TextBox

Posted on 2010-01-11
16
Medium Priority
?
3,819 Views
Last Modified: 2012-05-08
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

0
Comment
Question by:ewolsing
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 2
  • +2
16 Comments
 
LVL 10

Expert Comment

by:codingbeaver
ID: 26288449
Change it to:
Me.txtAreaCode.Attributes.Add("onkeypress", "DigitsOnly(e);")

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 26288451
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
 
LVL 10

Expert Comment

by:codingbeaver
ID: 26288514
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:experts1
ID: 26288527
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
 

Author Comment

by:ewolsing
ID: 26288993
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
 
LVL 82

Expert Comment

by:leakim971
ID: 26289006
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
 
LVL 82

Expert Comment

by:leakim971
ID: 26289013
with your controlS (asp:TextBox)
0
 

Author Comment

by:ewolsing
ID: 26289097
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
 
LVL 82

Accepted Solution

by:
leakim971 earned 2000 total points
ID: 26289158
Remove this tags:

    <![CDATA[

and :

    //]]>
0
 

Author Comment

by:ewolsing
ID: 26289223
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
 
LVL 5

Expert Comment

by:vb_student
ID: 26289247
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
 
LVL 82

Expert Comment

by:leakim971
ID: 26289250
only numeric : 0x30 to 0x39


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

Open in new window

0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 2000 total points
ID: 26289256
So :


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

Open in new window

0
 
LVL 5

Expert Comment

by:vb_student
ID: 26289280
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
 

Author Closing Comment

by:ewolsing
ID: 31675880
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
 
LVL 82

Expert Comment

by:leakim971
ID: 26289466
You're welcome! Thanks for the points and for sharing the final code! Happy new year!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question