Passing parameter to javascript function on textchange event of textbox in asp.net

I am deadly  trying  to make it , but no success,
Experts plz help me.

on any Text Change It is not prompting  any message box
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       
 txtpackage.Attributes.Add("onchange", "displaymessage(txtpackage.text)")
 
  End Sub
 
-----------------------
javascript code
------------------------
<html  >
<head runat="server">
    <title>Untitled Page</title>
       <script  language ="javascript" type="text/javascript" >
      function displaymessage(ch)
      {
        alert(ch);
      }
 
    </script>
</head>
<body>
 
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtpackage" runat="server"></asp:TextBox>
        <asp:Label ID="Label1" runat="server" Text="Label" Width="190px"></asp:Label></div>
    </form>
</body>
</html>

Open in new window

rajeev_23Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
sandsonConnect With a Mentor Commented:
hi rajeev_23,

I just built a sample web site using the code I posted above and it worked for me. I simply improved a little the javascript function to add the last typed key stroke when displaying the message box.

Can you try out the attached code (I created the Web site with Visual Studio 2005, using C# on .NET 2.0) and tell me if you still have problems ?

Best regards,
Abdel
///Default.aspx.cs 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
      if( !IsPostBack )
        txtpackage.Attributes.Add("onkeypress", "displaymessage(event, '" + txtpackage.ClientID + "');"); // If you want the event be fired for each key stroke
    }
 
////////////////////////////////////////////////
/// Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!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 runat="server">
  <title>Untitled Page</title>
 
  <script language="javascript" type="text/javascript">
      function displaymessage(e, txtId)
      {
        var txt = document.getElementById(txtId);
        if( txt == null ) return;
        alert(txt.value + String.fromCharCode(e.keyCode)); // to get all text in the text box
        //alert(String.fromCharCode(window.event.keyCode)); // cahracter just entered
      }
 
  </script>
 
</head>
<body>
  <form id="form1" runat="server">
    <div>
      &nbsp;<table style="width: 615px; height: 412px">
        <tr>
          <td style="width: 100px">
            <asp:GridView ID="GridView1" runat="server">
            </asp:GridView>
          </td>
          <td style="width: 100px">
          </td>
          <td style="width: 100px">
          </td>
        </tr>
        <tr>
          <td style="width: 100px; height: 42px">
          </td>
          <td style="width: 100px; height: 42px">
            <asp:TextBox ID="txtpackage" runat="server" Height="40px" Width="176px"></asp:TextBox></td>
          <td style="width: 100px; height: 42px">
          </td>
        </tr>
        <tr>
          <td style="width: 100px; height: 21px">
          </td>
          <td style="width: 100px; height: 21px">
          </td>
          <td style="width: 100px; height: 21px">
          </td>
        </tr>
      </table>
    </div>
  </form>
</body>
</html>

Open in new window

0
 
TimCotteeHead of Software ServicesCommented:
Hello rajeev_23,

The .text property does not apply to an html textbox. You need to use .value instead. If this is a more complex page with nested controls, you cannot necessarily guarantee that the control name is as you expect. A safer option in fact is to use "displaymessage(this.value);"

Regards,

TimCottee
0
 
Obadiah ChristopherCommented:
ya this.value should be passed....

And a better option to
txtpackage.Attributes.Add("onchange", "displaymessage(txtpackage.text)")


would be

txtpackage.Attributes.Add("onkeydown", "displaymessage(txtpackage.text)")

This will include the press of backspace also
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
TimCotteeHead of Software ServicesCommented:
informaniac,

OnChange doesn't worry about key presses of any kind, it only fires when focus moves from that control. Displaying an alert for every keypress could be a bit of a pain to handle for the user!

TimCottee
0
 
Obadiah ChristopherCommented:
Ok. will rember that, but as far as I know... onblur fires when the focus moves from textbox control....
0
 
sandsonCommented:
Hello rajeev_23,

by default the onchange is not fired as you type in the textbox, but only when it loses the focus (ie. when you click somewhere else in the page). So you may need to implement the event 'onkeypress' instead and as suggested by TimCottee use this.value instead of txtpackage.text

Regards,
Abdel
0
 
TimCotteeHead of Software ServicesCommented:
informaniac,

OnBlur does indeed fire when you lose focus, but onchange will only fire if the value of the element has changed at the same time so that you can easily differentiate between losing focus on an element that has not changed and one that has.

TimCottee
0
 
Obadiah ChristopherCommented:
Oh wow.. I din't know that.....
THanks very much....

But in case I want to do something like autosuggest text box then i would have to use a onkeydown event right?
0
 
TimCotteeHead of Software ServicesCommented:
informaniac,

Yes you would, either onkeydown/up/press depending on what key presses you need to handle. The three handlers do not necessarily trap all key events so as you pointed out backspace needs to be trapped in keyup/down but can't be in keypress.

TimCottee
0
 
rajeev_23Author Commented:
Experts,

this.value doesn't work's for it
any Expert who can solve my problem in C# or Vb in any one
now i am attaching C# code here


///onpage load
txtpackage.Attributes.Add("OnChange", "displaymessage(" + txtpackage.Text + ");");
 
//////////HTml code/////
<html xmlns="http://www.w3.org/1999/xhtml" >
 
<head id="Head1" runat="server">
    <title>Untitled Page</title>
       <script  language ="javascript" type="text/javascript" >
      function displaymessage(txtId)
      {
        alert(this.value); // to get all text in the text box
        //alert(String.fromCharCode(window.event.keyCode)); // cahracter just entered
      }
 
    </script>
         
   </head>
    
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<table style="width: 615px; height: 412px">
            <tr>
                <td style="width: 100px">
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
                </td>
                <td style="width: 100px">
                </td>
                <td style="width: 100px">
                </td>
            </tr>
            <tr>
                <td style="width: 100px; height: 42px">
                </td>
                <td style="width: 100px; height: 42px">
                    <asp:TextBox ID="txtpackage" runat="server" Height="40px" Width="176px"></asp:TextBox></td>
                <td style="width: 100px; height: 42px">
                </td>
            </tr>
            <tr>
                <td style="width: 100px; height: 21px">
                </td>
                <td style="width: 100px; height: 21px">
                </td>
                <td style="width: 100px; height: 21px">
                </td>
            </tr>
        </table>
    
    </div>
    </form>
</body>
</html>

Open in new window

0
 
TimCotteeHead of Software ServicesCommented:
rajeev_23,

That is not what we suggested, you should return your javascript function to the way it was. It is the attribute that you need to change:

txtPackage.Attributes.Add("OnChange","displaymessage(this.value);")

TimCottee
0
 
sandsonCommented:
Rajeev_23,

use the following snippets to get acces the textbox content.
///onpage load
txtpackage.Attributes.Add("onchange", "displaymessage('" + txtpackage.ClientID + "');"); // If you want the event be fired when losing focus
or
txtpackage.Attributes.Add("onkeypress", "displaymessage('" + txtpackage.ClientID + "');"); // If you want the event be fired for each key stroke
 
///HTML/JS code
       <script  language ="javascript" type="text/javascript" >
      function displaymessage(txtId)
      {
        var txt = document.getElementById(txtId);
        if( txt == null ) return;
        alert(txt.value); // to get all text in the text box
        //alert(String.fromCharCode(window.event.keyCode)); // cahracter just entered
      }
 
    </script>

Open in new window

0
 
Obadiah ChristopherCommented:
The only prblm is ' is missing

txtpackage.Attributes.Add("OnChange", "displaymessage(" + txtpackage.Text + ");");

should be

txtpackage.Attributes.Add("OnChange", "displaymessage('" + txtpackage.Text + "');");

0
 
rajeev_23Author Commented:
None of the above  suggested code is working
I am still trying
////////////C# code
 txtpackage.Attributes.Add("onkeypress", "displaymessage('" + txtpackage.ClientID + "');");
 
////////HTML Code
<head id="Head1" runat="server">
    <title>Untitled Page</title>
       <script  language ="javascript" type="text/javascript" >
      function displaymessage(txtId)
      {
        var txt = document.getElementById(txtId);
        if( txt == null ) return;
        alert(txt.value); // to get all text in the text box
        //alert(String.fromCharCode(window.event.keyCode)); // cahracter just entered
      }
 
    </script>
         
   </head>

Open in new window

0
 
sandsonCommented:
informaniac,

this solution can't work, as on page load server side the text propertie of txtpackage is empty so it will always show an empty message box. displaymessage to has to have either the actual value client side (this.value) or a reference to the html input itself (txtpackage.ClientID) so the function displaymessage can retrieve the value at runtime.

regards,
Abdel
0
 
Obadiah ChristopherCommented:
Please check wht is the output of this?

txtpackage.Attributes.Add("onkeypress", "displaymessage('" + txtpackage.ClientID + "');");


<script  language ="javascript" type="text/javascript" >
      function displaymessage(txtId)
      {
            alert(txtId);
return false;
      }
 
    </script>
0
 
sandsonCommented:
rajeev,

what do you get exactly using the code snippet I suggested ? a script error ? an empty message ? nothing ?

can you execute that page, then right click in your browser, choose 'View Source', then search for txtpackage (it should by <input type='text' id='...txtpackage..' ... />).

Copy and paste the search result (the input's source line) here so I can check if every thing went well from the server side to the client side.

regards,
Abdel
0
 
rajeev_23Author Commented:
It is not prompting any error but thing I want to do is not happening i.e. message box on entry of every Single character in textbox
0
 
sandsonCommented:
oops I forgot the class closing } in my code snippet above, don't forget to add it before testing.

Best regards,
Abdel
0
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.

All Courses

From novice to tech pro — start learning today.