Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2008-09-29
21
Medium Priority
?
4,633 Views
Last Modified: 2013-11-07
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

0
Comment
Question by:rajeev_23
[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
  • 6
  • 5
  • 5
  • +1
21 Comments
 
LVL 43

Expert Comment

by:TimCottee
ID: 22595383
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
 
LVL 20

Expert Comment

by:informaniac
ID: 22595455
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
 
LVL 43

Expert Comment

by:TimCottee
ID: 22595494
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
Stressed Out?

Watch some penguins on the livecam!

 
LVL 20

Expert Comment

by:informaniac
ID: 22595503
Ok. will rember that, but as far as I know... onblur fires when the focus moves from textbox control....
0
 
LVL 2

Expert Comment

by:sandson
ID: 22595537
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
 
LVL 43

Expert Comment

by:TimCottee
ID: 22595593
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
 
LVL 20

Expert Comment

by:informaniac
ID: 22595614
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
 
LVL 43

Expert Comment

by:TimCottee
ID: 22595640
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
 

Author Comment

by:rajeev_23
ID: 22595653
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
 
LVL 43

Expert Comment

by:TimCottee
ID: 22595665
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
 
LVL 2

Expert Comment

by:sandson
ID: 22595688
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
 
LVL 20

Expert Comment

by:informaniac
ID: 22595735
The only prblm is ' is missing

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

should be

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

0
 

Author Comment

by:rajeev_23
ID: 22595775
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
 
LVL 2

Expert Comment

by:sandson
ID: 22595830
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
 
LVL 20

Expert Comment

by:informaniac
ID: 22595861
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
 
LVL 2

Expert Comment

by:sandson
ID: 22595871
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
 

Author Comment

by:rajeev_23
ID: 22639664
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
 
LVL 2

Accepted Solution

by:
sandson earned 2000 total points
ID: 22667055
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
 
LVL 2

Expert Comment

by:sandson
ID: 22667059
oops I forgot the class closing } in my code snippet above, don't forget to add it before testing.

Best regards,
Abdel
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

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

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

721 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