Solved

Need to enable a button in asp.net on the basis of changing test in the Textbox + jquery

Posted on 2010-09-21
37
861 Views
Last Modified: 2012-05-10
Hi, I need to enable the button in ASP.NET on the basis of text changed in ASP.NET textbox. using jquery.
I need to do it in the code behind of the asp.net page
0
Comment
Question by:Ammar Iqbal
  • 20
  • 15
  • +1
37 Comments
 
LVL 22

Expert Comment

by:Ivo Stoykov
ID: 33723828
jquery is on the client. it has nothing with code behind.

Please check the snippets attached

HTH

Ivo Stoykov

// code bihind
Button1.Enable = !TextBox1.Text.Equals("Text to search for disabling");

// jquery
$('#<%=Button1.ClientID %>').enable($('#<%=TextBox1.ClientID%>).text() == "Text to search for disabling");

Open in new window

0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33723866
where to add this jquery line...in the code behind or on the aspx page
0
 
LVL 5

Expert Comment

by:roxviper
ID: 33723913
aspx page
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33723933
Hello,

In aspx page as shown below in code:

Regards,
VSS

<script type="text/javascript">
        $('#<%=Button1.ClientID %>').enable($('#<%=TextBox1.ClientID%>).text() == "Text to search for disabling");
</script>

Open in new window

0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33723950
but i don't want to searc ha text for display. i need to do it when there is any change in the textbox's text
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33724087
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33724112
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33724348
I am doing this in the PageLoad method :
 txtEmail.Attributes.Add("onchange", "document.getElementById('btnEmail').enabled=true");
 txtMobile.Attributes.Add("onchange", "document.getElementById('btnMobile').enabled=true");

The problem is that when i changes the email or mobile number and triesto press the btnemail or btn mobile,
i get the Microsoft J runtime error "document.getElementById(---)" is null or not an object.
both the buttons are disabled,I want them to be enabled when ever i changes the text in the textbox .but they are not gettting enabled , and are giving the above Microst Java runtime error
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33724617
Hi,

I think it should be as in code attach. Try and let us know back if problem persists.

Regards,
VSS

txtEmail.Attributes.Add("onchange", "javascript:document.getElementById('btnEmail').enabled=true");
 txtMobile.Attributes.Add("onchange", "javascript:document.getElementById('btnMobile').enabled=true");

Open in new window

0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33724647
same problem... and error.
i thope you have understood my question..once i change the email or mobile, the corresponding buttons gets enabled. But  it is not getting enabled and also giving the microosft j runtime error
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33724935
Hi,

Try code as following. (There is no enabled property for elements).

Regards,
VSS

txtEmail.Attributes.Add("onchange", "javascript:document.getElementById('btnEmail').disabled=false");
 txtMobile.Attributes.Add("onchange", "javascript:document.getElementById('btnMobile').disabled=false");

Open in new window

0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33725017
same error :(

I am not figuring out ,what could be the problem. This is straight forward. the button should gets enabled once the text is changed. same erro is coming which is "object is null or not and object-"
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33725069
Hmm... OK.... !

Let me know which browser you are using. And if possible show me your aspx code (if you can).
Because the same above code is working fine for me on Mozilla Firefox 3.5 and IE 5.1.

See code for my simple application. I executed code. Enter some value in any of textbox... and after shifting focus to other control the button gets enabled.

Regards,
VSS

---------------
//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>TextBox Attributes</title>
    <script type="Text/javascript">
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtEmail" runat="server" /><br />
    <asp:TextBox ID="txtMobile" runat="server" />
    <asp:Button ID="btnEmail" runat="server" Text="Email" Enabled="false" />
    <asp:Button ID="btnMobile" runat="server" Text="Mobile" Enabled="false" />
    </form>
</body>
</html>

----------------
//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)
    {
        txtEmail.Attributes.Add("onchange", "javascript:document.getElementById('btnEmail').disabled=false");
        txtMobile.Attributes.Add("onchange", "javascript:document.getElementById('btnMobile').disabled=false");
    }
}

Open in new window

0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33725148
I have tried it but same error. i have my aspx page.it is a lonf gfile, but you can look at the btnEmail and btnMobile., page load method of the code behind is also pasted

<%@ Page Title="Edit User Settings" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="ChangePassword.aspx.cs" Inherits="CautusGeo.ChangePassword" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
   
    <style type="text/css">
        .style1
        {
            width: 408px;
        }
        .style4
        {
            width: 283px;
        }
        .style7
        {
            width: 139px;
        }
        .style8
        {
            width: 137px;
        }
        .style12
        {
            width: 16px;
        }
        .style13
        {
            width: 22px;
        }
        .style15
        {
            width: 9px;
        }
        .style16
        {
            width: 7px;
        }
    </style>
   
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
     <div id="div1" runat="server" class="portlet-content">
      <script language="javascript" type="text/javascript">
   

      </script>
     <table>
        <tr>
            <td class="style1">
                   <span class="validate_error"> New passwords are required to be of minimum<%= Membership.MinRequiredPasswordLength%> characters in length</span>
            </td>
       </tr>
     </table>
     
     

    <asp:ChangePassword ID="ChangeUserPassword" runat="server" CancelDestinationPageUrl="~/Admin/Admin.aspx" EnableViewState="false" SuccessPageUrl="ChangePasswordSuccess.aspx" Width="268px">
      <ChangePasswordTemplate>
         <asp:ValidationSummary ID="ChangeUserPasswordValidationSummary" runat="server" ValidationGroup="ChangeUserPasswordValidationGroup"/>
            <table>
               <tr>
                  <td class="style1">
                      <asp:Label ID="CurrentPasswordLabel" runat="server"  AssociatedControlID="CurrentPassword" Width="132px" Height="18px">Old Password:</asp:Label>
                  </td>
                           
                  <td>
                     <asp:TextBox ID="CurrentPassword" runat="server"  TextMode="Password" Width="280px" ></asp:TextBox>
                  </td>
                   
                  <td class="style16">
                      <asp:RequiredFieldValidator ID="CurrentPasswordRequired" runat="server"   ForeColor="Red" Font-Size="X-Large" Font-Bold="true" ControlToValidate="CurrentPassword"  ValidationGroup="ChangeUserPasswordValidationGroup">
                      *</asp:RequiredFieldValidator>
                  </td>
              </tr>
                     
              <tr>
                 <td class="style1">
                    <asp:Label ID="NewPasswordLabel" runat="server" AssociatedControlID="NewPassword" Height="16px" Width="105px">New Password:</asp:Label>
                 </td>
                           
                 <td>
                    <asp:TextBox ID="NewPassword" runat="server"  TextMode="Password" Width="280px"></asp:TextBox>
                 </td>
                   
                 <td class="style16">
                    <asp:RequiredFieldValidator ID="NewPasswordRequired" runat="server" ControlToValidate="NewPassword" ForeColor="Red" Font-Size="X-Large" Font-Bold="true" ValidationGroup="ChangeUserPasswordValidationGroup">
                    *</asp:RequiredFieldValidator>
                 </td>
              </tr>
                     
              <tr>
                 <td class="style1">
                   <asp:Label ID="ConfirmNewPasswordLabel" runat="server" AssociatedControlID="ConfirmNewPassword" Width="142px">Confirm New Password:</asp:Label>
                 </td>
                         
                <td>
                    <asp:TextBox ID="ConfirmNewPassword" runat="server"  TextMode="Password" Width="280px"></asp:TextBox>
                </td>
                <td class="style16">
                    <asp:RequiredFieldValidator ID="ConfirmNewPasswordRequired" runat="server" ControlToValidate="ConfirmNewPassword" CssClass="" Display="Dynamic"  ForeColor="Red" Font-Size="X-Large" Font-Bold="true" ValidationGroup="ChangeUserPasswordValidationGroup">*</asp:RequiredFieldValidator>
                </td>            
                           
                 <td class="style12">
                    <asp:CompareValidator ID="NewPasswordCompare" runat="server" ControlToCompare="NewPassword" ControlToValidate="ConfirmNewPassword" CssClass="" Display="Dynamic" ForeColor="Red" Font-Size="X-Large" Font-Bold="true"
                                ValidationGroup="ChangeUserPasswordValidationGroup">*</asp:CompareValidator>
                 </td>
                         
                 <td>
                    <class="submitButton">
                    <asp:LinkButton ID="ChangePasswordPushButton" CssClass="button" runat="server" CommandName="ChangePassword" ValidationGroup="ChangeUserPasswordValidationGroup"><span class="ui-icon ui-icon-arrowrefresh-1-w"></span>Change Password
                    </asp:LinkButton>
                 </td></tr></table></ChangePasswordTemplate></asp:ChangePassword><table>
           <tr>
               <td  class="style8"><asp:Label ID="lbNewEmail" runat="server" AssociatedControlID="txtEmail"  Height="16px">Email:</asp:Label></td><td>
                   <asp:TextBox ID="txtEmail" runat="server" Width="280px"  onchange="return EnableButton();" ></asp:TextBox></td><td
                      class="style16"><asp:RequiredFieldValidator ID="valRequireEmail" runat="server" ControlToValidate="txtEmail" SetFocusOnError="true"
                        Display="Dynamic" ErrorMessage="Email address is required." ToolTip="Email address is required." ValidationGroup="ChangeEmail"  ForeColor="Red" Font-Size="X-Large" Font-Bold="true"
                        Text="*" />        
                    <asp:RegularExpressionValidator  ID="valEmailPattern" Display="Dynamic" runat="server" SetFocusOnError="true"  ValidationGroup="ChangeEmail" ControlToValidate="txtEmail"
                       ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ErrorMessage="The e-mail address you specified is not well-formed." ForeColor="Red" Font-Size="X-Large" Font-Bold="true" Text="*" />      
              </td>
         
               <td>        
                  <asp:LinkButton ID="btnEmail" CssClass="button" runat="server"  OnClick="btnEmail_Click" OnClientClick=""  ValidationGroup="ChangeEmail" Enabled="false" ><span class="ui-icon ui-icon-arrowrefresh-1-w"></span>Change Email</asp:LinkButton></td><td>
                  <asp:Label  ID="lbEmailChangeSuccess" runat="server" EnableViewState="false" />
              </td>  
          </tr>
             
   </table>        
   
       


           
 
  <table>
      <tr>
             <td class="style7"><asp:Label ID="lbMobile" runat="server" AssociatedControlID="txtMobile" Width="83px" Height="16px">Mobile #:</asp:Label></td><td class="style4">
                <asp:TextBox ID="txtMobile" runat="server" Width="280px"  ></asp:TextBox></td><td class="style16">
                &nbsp;
            </td>
           
            <td>
              <asp:LinkButton ID="btnMobile" CssClass="button" runat="server"   OnClick="btnMobile_Click" ValidationGroup="ChangeMobile"  Enabled="false"><span class="ui-icon ui-icon-arrowrefresh-1-w"></span>Change Mobile #</asp:LinkButton><asp:Label runat="server" ID="lbMobileChangeSuccess" EnableViewState="false" />
            </td>          
     </tr>
 </table>    
 </div>
</asp:Content>

 <asp:Content ID="Content3" ContentPlaceHolderID="SidebarContent" runat="Server">
         <h2>Account Settings</h2><ul runat="server" id="ulMenu" />
</asp:Content>

______________________________________________________________________________
code behind
protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
               
             
                     //txtEmail.Attributes.Add("onchange", "$(#" + btnEmail.ClientID + ").enable();");
           //  txtEmail.Attributes.Add("onchange", "document.getElementById('btnEmail.ClientId').disabled=false");
           
            txtEmail.Attributes.Add("onchange", "javascript:document.getElementById('btnEmail').disabled=false");
            txtMobile.Attributes.Add("onchange", "javascript:document.getElementById('btnMobile').disabled=false");
           
        }
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33725177
i am using internet explorer , the one on Windows 7
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33725330
do i need to write something in aspx page.?
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33725372
Hi,

I am wondering why your compiler is not showing you error when you are trying to build your .aspx.cs page.

Since you are using Master page. So you cannot access these controls directly. You would need to access controls by referencing Master Page controls. I am trying for its working. Please wait...

Regards,
VSS
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33725419
everything else on the page and the project is working fine.. except this stuff :(
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33725424
and the controls is on this page, not on the masters page
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33725430
That would fine within few minutes. I am online and solving it.
0
 
LVL 16

Accepted Solution

by:
Vikram Singh Saini earned 500 total points
ID: 33728163
Hi,

Please check link:
http://niitdeveloper.blogspot.com/2010/09/how-to-use-javascript-with-master-pages.html

And let us know if problem still persists.

Regards,
VSS
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33731932
yes it is working, but it gets enabled , once i leave the control after changing the text, is it possible, it should gets enabled, as soon i changed the text in the text box. so that i do not have to leave it. Secondly, the call back for both the buttons are not working. the purpose is that if buttons get enabled,then i have t ochange the email address by clicking on it,  once the email is changed, then it gets disabled after updated the email address and mobile number in the db
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33732458
It works if i use onchange insteead of onkey down. The button gets enabled once i click on it. Bit is there any way as soon as i changed the text in the text box, the button gets automatically enabled., and thus subsequently calls the event handler of the but the "btnEmail" and "btnMobile".
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33732886
Hi,

(1) but it gets enabled , once i leave the control after changing the text,  is it possible, it should gets enabled, as soon i changed the text in  the text box


I have tested the code both on Mozilla Firefox 3.6.3 and IE 5.1. It enables button as soon a key is pressed down in textboxes. So it could be browser specific problem (I think..).

(2) It works if i use onchange insteead of onkey down.
When I tried for OnChange I was having above problem (1) as mentioned by you. So again I would say browser specific problems.

(3) thus subsequently calls the event handler of the but  the "btnEmail" and "btnMobile".                            
So you want to call event handlers of these two buttons as they gets enable. I would try same & would let you know.

Regards,
VSS
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33732900
yes the buttons have got their respective event handlers in the code behind, something to do with triggering of jquery's click event
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33733350
Hi,

You cannot call server side code from client side code. But there exists some alternative for the same. Here is the link from which you can get refernce:

http://www.dotnetcurry.com/ShowArticle.aspx?ID=109&AspxAutoDetectCookieSupport=1

Regards,
VSS
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33733399
but i need to call the twoevent handlers behind thetwo buttons, once they are enabled. there is a method of Jquery triggr or click.. do oyu have soem idea about that
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33733474
the main thing is that i need to fire onclick event of both these buttons. i think it sohuld fire,because once the buttons are enabled, there shouldn't be any problem for him to fire
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33733507
Ok! Let me check the same for jquery too.
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33733515
but at the moment when i click on the enabled buttons,it gives me a jscript runtime error...object expected
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33733663
Hi,

In that case I need answer to some questions:

(1) it gives me a jscript runtime error...object expected                            
Show me full error details. And also attach a screenshot showing error you are facing. I want to know all details.

(2) Also let me know your modified code (.aspx page) and also share .aspx.cs. Seems there is error in some other code. And while sharing code please paste the code in the code section given in below comment option. It helps in easy readability.

Regards,
VSS
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33733890
 I have attached the code snippet... i need to trigger  the serversdie event handler of the button Email  "btnEmail_Click()" to update/change  the email through jquery. but its not been triggering.
aspx.cs page    

Page_Load

{

               txtEmail.Attributes.Add("OnKeyDown", "EnableEmail()");

                txtMobile.Attributes.Add("OnKeyDown","EnableMobile()");



                btnEmail.Attributes.Add("OnClick", "UpdateEmail()");

                btnMobile.Attributes.Add("OnClick", "UpdateMobile()");

}



////////////////////////////////////////

.aspx page

<script type="text/javascript">

          function EnableEmail()

          {

            $("#<%=btnEmail.ClientID%>").attr('disabled', false);

          }



          function EnableMobile()

          {

            $("#<%=btnMobile.ClientID%>").attr('disabled', false);

          }

          function UpdateEmail()

          {

           $(".btnEmail").click(function() {

              btnEmail_Click();

             $("#btnEmail").trigger("click"); ;

  

              });  

          }

          function UpdateMobile() 

          {



          }

       </script>

Open in new window

0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33734425
I think whiling enabling the buttons on the client. There is no way for the server to know, that buttons have been enabked, otherwise it is simolething that server event handlers behinds the buttons are called
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33736629
Hi,

I will try my best to get you solution for the thing you are trying in jquery. But I would respond you tomorrow evening. Currently I am busy with preparation for interview.

Regards,
VSS
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33741861
have you tried it lately?
0
 
LVL 1

Author Comment

by:Ammar Iqbal
ID: 33751809
Ihave found the solution, actually i was disabling both the buttons on the server side at the time of initiailizong or loading the page.. Needed t odisable them on client side instead of the server side
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33759535
Hi,

That's nice that at last you reach to solution by hit and trial method.

Happy Programming.

Regards,
VSS
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

707 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

13 Experts available now in Live!

Get 1:1 Help Now