Solved

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

Posted on 2008-09-29
21
4,405 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
  • 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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 500 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

808 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