Solved

calling a function inside a textbox control from a kepress event?

Posted on 2004-10-19
16
785 Views
Last Modified: 2008-02-01
HI There,

I have a webform and I am wanting to call a function from a textbox control located on the webform when a key is pressed. Can this be done and if so, does anyone have an code to get me started?

Sean
0
Comment
Question by:bullrout
  • 6
  • 5
  • 2
  • +3
16 Comments
 
LVL 10

Expert Comment

by:jnhorst
Comment Utility
Yes:

In your Page_Load event, if the page is NOT a postback, do this:

txtTextBox.Attributes.Add("onkeypress", "javascript:yourFunction();");

If your function validates the key pressed and cancels the event if the keyCode is not a valid keyCode in your function, you might want to use the "onkeydown" event instead.

John
0
 
LVL 26

Assisted Solution

by:Rejojohny
Rejojohny earned 200 total points
Comment Utility
do u mean a client-side script on key press .. if s, then do this ..
assuming ur textbox is called textbox1

on ur ASPX page .. write this code within javascript tags
<script laguage=javascript>
function trapKeypress() {
 alert (window.event.keyCode);
}
</script>

and in ur .vb page of the .aspx page .. add this line in the load event of the page
textbox1.attributes.item("onkeypress") = "javascript:trapKeypress();"
0
 
LVL 5

Author Comment

by:bullrout
Comment Utility
Hi There,

is it possible to call a vb.net function from something like this?
0
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
no ... this is not to call any vb.net function .. i hope u meant vb.net as code-behind ...

this is call client-side scripts to be called by the browser .. so u want to trap keypress on the server?? why would u want to do it .. I hope u understand the omplexity behind such a functionality .. on every keypress, the form has to be submitted .. or atleast use some remotescripting to make calls to code-behind functions .. also there is no keypress server side event handler .. u will have to use the "onchange" event  .. still i wouldn't advise that .. if u could explain what u r trying to do, i might be able to suggest an alternative solution ...
0
 
LVL 5

Author Comment

by:bullrout
Comment Utility
Hi Rejojohny,

I did mean I want to call a function inside the code behind. What I want to do is to have a textbox and then when a user types a character the textbox is populated with the first entry inside the db of what they typed. For example if the user types "a" then the textbox would be populated with the first entry inside the table that began with "a".

I did toss up some different methods, populating a listbox with all of the entries and then selecting from this when the key is pressed.

Do you have any ideas?
0
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
normally I would use a dropdownlist for a similar scenario ... fill the dropdownlist with all the values from the database and dropdownlist has the functionality u have mentioned ... i.e. defauting to the first value found in the list.

if that doesn't suit ur needs . then based on ur requirement u will have to use the onchange event of textbox ... write ur code to populate the textbox from the databse in the onchange event (code-behind) of the textbox.But mind that this is not going too user friendly and excessive processing ...
0
 
LVL 5

Author Comment

by:bullrout
Comment Utility
How do I call the non-javascript function from the event on the textbox control?
0
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
what do u mean by "non-javascript function" .. u mean code-behind? if s .. just double click on the textbox during design-time and it will open the code-behind (.vb page) .. write ur code there.. or u could also write code on ur .aspx page by specifying a script tag as runat=server .. like this

<script lanaguage=vb runat=server>

</script>

but i would not advise u to do this .. do it the other way as mentioned above ...
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 5

Author Comment

by:bullrout
Comment Utility
Hi There,

I double clicked on the textbox and it produced the following code, (i added the label in) but to populate it I need to hit the enter key. How can I envoke this event with a keypress?

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Label1.Text = "sean"
    End Sub
0
 
LVL 2

Expert Comment

by:raed_hasan
Comment Utility
I also recommend to do the ways suggested above like Rejojohny  code, if u want to do something on server side You can submit the form in trapKeypress() ( as Rejojohny posted ). This will cause a postback and
you can pass to the server a sort of info telling what exactly caused the postback. This will resemble a server event.  You can't avoid using javascript on the client side.

 How can server know what is happening in the browser?
0
 
LVL 5

Author Comment

by:bullrout
Comment Utility
ok I get what your saying, I was just hoping that another method was available to me.

Sean
0
 
LVL 44

Expert Comment

by:Arthur_Wood
Comment Utility
trust me, what you THINK you want to do is a very bad idea.  It would be sort of like the following:

You and your 'significant other' go to a restaurant, for dinner.  The restaurant owner has decided that he wants to make sure that every partron gets the latest information about the availability of the choices on the menu, as they order, so after every word uttered by a patron, the waiter is to check with the kitchen to make sure that all of the choices on the menu that begin with the words spoken by the patron are still available.  That means that every time a patron says a word, the waiter must run into the kitchen, ask the chef if the items are still available, and run back to the table, to let the patron know that those items are still available, so that the patron can then add another word to the order, and the process is repeated.  Is that what you really want.  After every keypress, in order to execute a server-side function, the page must be submitted back to the server, the function executed, and the page returned back to the client.  That will make the page be VERY VERY slow.

AW
0
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
good example arthur :-) i have been trying to tell the same thing .. that the whole idea is bad. .. use a dropdownlist instead ... anyway thought "bullrout" might be trying some things out and might have some other genuine reason for designing such a form ..
0
 
LVL 18

Expert Comment

by:tusharashah
Comment Utility
To enable this function,

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Label1.Text = "sean"
    End Sub

---> You need to Set AutoPostBack=true in the Property of your TextBox.

This function will only be called once the focus will go out of TextBox & only if the Text inside that TextBox has been changed. & Page will be slow but not very very slow..(dont take it personally AW).. As, the page will post back only in the condition I stated above.!

-tushar
0
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
>>How can I envoke this event with a keypress?
autopostback of the textbox has to be set to true
0
 
LVL 10

Accepted Solution

by:
jnhorst earned 300 total points
Comment Utility
There is a way to do this client side with a textbox.  Get your data from the database into a data reader.  Iterate through the records in the data reader, appending each value to a comma delimited string.  Then write a <script></script> block to the browser in your Page_Load event that uses this comma delimited string to create an array (in JavaScript, this in the <script></script> block).  Then you could code a function for the onkeyup event of the textbox that would iterate through that array, and if it found a member that had the same first letter, it would populate the text box with that member.

Put this in your <head></head> section in the aspx page:

<script language="javascript">
// this is IE javascript.  Probably will not work right in other browsers.
function checkArray()
{
      // get keycode.
      var key = event.keyCode;
                  
      // test for certain keys.
      var test1 = (key == 37 || key == 39);            // 37 & 39 are left/right arrow keys.
      var test2 = (key == 46 || key == 9);            // 46 & 9 are delete and tab keys.
      var test3 = (key == 8  || key == 13);            // 8 is backspace. 13 is enter.
                  
      // ignore those keys in the tests.
      if (!test1 && !test2 && !test3)
      {
            for (i=0; i<arrList.length; i++)
            {
                  if (arrList[i].substring(0, 1).toLowerCase() == event.srcElement.value.toLowerCase())
                  {
                        event.srcElement.value = arrList[i];
                        break;
                  }
            }
      }
}
</script>

Then put this in Page_Load.

if (!this.IsPostBack)
{
                // I hard coded the string values here.  You would create this string by iterating through your data reader.
      string vals = "Abc,Bcd,Cde,Def,Efg,Fgh,Ghi,Hij,Ijk,Jkl";

                // you will register this block with the page to create the array that your checkArray() function will use.
      string js = "<script language=\"javascript\">\n";
      js += "var list = '" + vals + "';\n";
      js += "var arrList = list.split(\",\");\n";
      js += "</script>";

                // this causes the script defined above to be rendered to the browser.
      this.RegisterStartupScript("list", js);
               
                // this will add the onkeyup event to the textbox when it renders.
                this.txtBox.Attributes.Add("onkeyup", "javascript:checkArray();");
}

John
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now