Solved

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

Posted on 2008-09-29
21
4,439 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
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!

 
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

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

749 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