Correctly Enabling/Disabling an ASP.Net Button Control via Javascript

Inside of an AJAX Update Panel I have this control:

 <asp:Button ID="buttonDiscard" runat="server" Text="Discard" Enabled="false" style="font-size:10px" OnClientClick="return GetConfirmation();" OnClick="buttonDiscard_Click" />

The part highlighted in bold is something I just added.  It's simply calling this:

    function GetConfirmation() {
      debugger
      var answer = confirm('Are you absolutely sure you want to throw away this past editing you have done?');
      if (answer)
      {
        alert("Okay, now will run server-side code")
      }
      else
      {
        return false;
      }
    }

On the page, this button is enabled & disabled depending on several things.  That Javascript code *appears* to be working correctly in that I can visually see the button becoming enabled & disabled as I would expect.  BUT the problem is that the client-side GetConfirmation function is NOT being executed.  It's as if the client-side event handler is somehow being removed from the button.

When I added a test button that I just left enabled constantly, it did call this client-side function!

Any ideas why I'm experiencing what I am?

Robert


Robert Werner
Vancouver, BC
www.mwtech.blogspot.com
www.pocketpollster.com/beta
-1
rmdw
5/4/2009 11:23:36 PM
asp.net.client-side 24353 articles. 2 followers. Follow

12 Replies
4376 Views

Similar Articles

[PageSpeed] 20

  

    Protected Sub buttonDiscard_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonDiscard.Click
        ScriptManager.RegisterStartupScript(Me, Me.GetType(), "confirmation", "GetConfirmation();", True)
    End Sub
 
When you ask a question, remember to click "Mark As Answer" when you get a reply which answers your question.
0
Kulrom
5/5/2009 12:27:51 AM

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="false">

 from this http://forums.asp.net/t/1069384.aspx?PageIndex=3

0
mo
5/5/2009 2:24:33 AM

I think that I did not explain the problem properly.  I don't believe there's anything wrong with my client-side code.

To get to the root of this problem please download this demo project I just created.  When you run it, it's fairly self-explanatory. Clearly there's something wrong with the approach I'm using to enable the first button.

Incidentally, to see how things will work when the button is enabled, just go to the Page_Load event handler and comment out the two lines of code within.  Then run the project again.

My belief is that if I can figure out how to properly enable the button with client-side code then the Javascript code attached to that button will run once more.

Robert

 


Robert Werner
Vancouver, BC
www.mwtech.blogspot.com
www.pocketpollster.com/beta
-1
rmdw
5/5/2009 3:47:30 AM

did you try this?

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="false">

-1
mo
5/5/2009 3:56:35 AM

how about

<asp:Button ID="Button2" runat="server" Text="Enable Delete Button" OnClientClick="enableDelete();return false;" />

-1
mo
5/5/2009 4:08:40 AM

 Hi rmdw,

As per the demo you provided, it's obvious behaviour. Look at your code..

<asp:Button ID="Button2" runat="server" Text="Enable Delete Button" OnClientClick="enableDelete();" />

what it will do is call javascript function then postback the page. So, it will first enable the button and then return the response from serverside which again make it disabled. The solution is very easy.. Just stop it to postback the page. using return false;

<asp:Button ID="Button2" runat="server" Text="Enable Delete Button" OnClientClick="enableDelete();return false;" /> 


Please mark as Answer if it helps u. Thanks!

Parth Patel
Techsture Technologies
Software Developer
Ahmedabad
-1
Coool
5/5/2009 4:25:05 AM

Your EnablePartialRendering="false" didn't seem to change anything.

Modifying OnClientClick of Button 2 as you did, seemed to resolve the immediate problem.  A question though: Why did the Delete button become disabled immediately after the server-side code was run?  I put a breakpoint on the server-side code in Page_Load and Button1.Enabled = false;  was NOT executed.  So what on earth is disabling the Delete button again?

There's clearly something I'm not understanding here!

Robert

 


Robert Werner
Vancouver, BC
www.mwtech.blogspot.com
www.pocketpollster.com/beta
-1
rmdw
5/5/2009 4:28:24 AM

Parth,

I'm reading your posting after I posted my last one.  I now understand what you mean.  OnClientClick has to return false or else the server-side code is executed.

Tell me something though, why is Button1 being disabled again after running the server-side code?  As I just stated previously, I put a break point on  Button1.Enabled = false  and it is definitely NOT being run again.

Making progress but still confused about this remaining issue,

Robert


Robert Werner
Vancouver, BC
www.mwtech.blogspot.com
www.pocketpollster.com/beta
-1
rmdw
5/5/2009 4:33:39 AM

glad to solve the problem ^_^

you can put the return false in the enableDelete()

and change enableDelete to return enableDelete()

-1
mo
5/5/2009 4:52:03 AM

 hi rmdw,

Whenever postback occurs, asp.net load page control value and property from ViewState and value which is posted back to the server. Now, any of the style property is not posted back to the server, nor any server side code is set it enabled on post back, so obviously it's not going to enable the button1.

What you can do is use one hidden Asp Control and then set value of it whenever button is enabled. Check the value of hidden asp control on server side and on the bases of that enable and disable button on postback. like

 

<!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></title>

  <script type="text/javascript">
    function confirmation() {
      var answer = confirm("Are you sure you want to do this?");
	    if (answer)
        alert("About to run server-side code...");
	    else
        return false;  
	  }

	  function enableDelete() {
	    $get('<%= hdnButton1State.ClientID %>').value = "1";
        $get('<%= Button1.ClientID %>').removeAttribute('disabled');
	  }
  </script>
</head>

<body>
  <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
      <ContentTemplate>
        <h2>Why does the second button not enable the first button?</h2>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Delete" OnClick="Button1_Click" OnClientClick="return confirmation();" />
        <br /><br />
        <asp:HiddenField ID="hdnButton1State" runat="server" Value="" />
        <asp:Button ID="Button2" runat="server" Text="Enable Delete Button" OnClientClick="enableDelete();return false;" />
        <br /><br /><br /><br />
        <asp:Label ID="Label1" runat="server" Text="Server-side code executed!" Visible="false" />
      </ContentTemplate>
    </asp:UpdatePanel>
  </form>
</body>
</html>
   
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Confirmation_Dialog_Box
{
  public partial class _Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      // Comment out these next two lines to see the code run normally
        if (hdnButton1State.Value == "1")
            Button1.Enabled = true;

      if (!IsPostBack)
        Button1.Enabled = false;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
      Label1.Visible = true;
    }
  }
}
 
Please mark as Answer if it helps u. Thanks!

Parth Patel
Techsture Technologies
Software Developer
Ahmedabad
0
Coool
5/5/2009 4:55:22 AM
as simple as put this property in button 1 

EnableViewState="false"

-1
mo
5/5/2009 4:59:11 AM

Thanks gents.  I created the test project to demonstrate to you the problem I'm having in my main project.  When now trying to implement the same code in my main project, I can't get the client-code to fire at all.  Instead it just immediately executes the server-side code.  Ughhhh.

Well, it's late here in Vancouver.  I'm going to get some sleep and try again tomorrow.

Thank you both for your help!

Robert

 


Robert Werner
Vancouver, BC
www.mwtech.blogspot.com
www.pocketpollster.com/beta
-1
rmdw
5/5/2009 5:03:06 AM
Reply:

Similar Artilces:

disable in vb.net
 I have a control that i am disabling in vb.netMe.chkEditGuestRSVPStatus.Enabled = FalseI would like to  enable it via javascript:$get('chkEditGuestRSVPStatus').disabled = false; but this does not work - it still stays disabled.Your help is appreciated.  If you do a view source on the rendered page, can you find a checkbox with that id? In certain situations, ASP.NET mangles the id of the control so that it's not really "what you see is what you get". There's the concept of naming container, which adds a prefix to the controls to ensure they ar...

Client-Side enabling of a Server-Side disabled control?
Recently I came into a situation that required me to enable a control client-side, which was previously disabled server-side. Let me explain using a checkbox as an example. When I run chkMyCheckBox.enabled = false, the resulting HTML includs a dynamically created a span that encloses the control. This span is does not have an ID and has the attribute disabled="disabled". This inturn disables the control and it's associated label. Problem being, I see a way to enable the control on the client-side, which requires me to enabled the span as well. Has anyone needed to do this bef...

Validation Controls in .NET ( Client side or server side?)
 i have a very basic question. We have all these validation controls in asp.net ( required field, range validator and others)..my question is the required field validator is a server side control. So does that mean that it does a post back?..is it client side or server side control  The only controls that post back are buttons and other inputs where you set AutoPostback="True", such as a dropdownlist or a textbox.  Another way of posting back is using an UpdatePanel and placing a trigger in it for a specified control and/or event. All controls are considered clien...

Validators
Hello, I've come across the problem when I wanted to use client side validation (no matter of which type) depending on the input from a different control. The scenario is: I have two textboxes A and B. A does not need to be validated (no validator associated with A). The textbox B has to be validated if and only if the A has any value. I know this is trivial with custom validator in the server side mode... But unfortunately I want it to run the validation on the client side. And I also know that I can write a javascript function for the ClientValidationFunction and hardcode client id ...

.Net varible into client side JavaScript
I'm need to get a variable from my web app and place its value in a JavaScript. I tried doing this with a Label but I get the HTML included. I don't think I can use the <%# %> from classic ASP? Anyone have any ideas on how they would approach this problem? tbone_stl wrote:Anyone have any ideas on how they would approach this problem? Hi, and welcome to the ASP.NET forums. It's possible to pass a variable to a javascript function. I created a small coding snippet: <%@ Page Language="C#" %>   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http...

Enable/Disable validation control client side
Hello - I was wondering if it possible to disable or enable a validation control through javascript alone. Basically, I have a check box. If the user ticks it, I then require them to fill in a text box. So, ideally, I'd have a requiredFieldValidator for the test box that would only be enabled when the user clicks the text box. Thing is - I'd rather do that without having to post back to the server to disable or enable the validation control.. Any ideas?? Thanks.http://www.developdesign.co.uk/ To disable or enable server validation control in ASP.NET using JavaScript:   Use the f...

diasbling controls via javascript client-side
hi,   is it possible to disable a complete <div> by using a client-side javascript ?   if so how ?  at the moment i am having to make the <div> visible/non-visible. I would rather just disable it so that the  user can see that there is another option available if they choose. cheers. Ya, you can. Give an ID for your DIV ( is it <asp:Panel> ?). Then in your JavaScript, document.getElementById("MyDIV").disabled = true;Alternatively, you can enable/disable the DIV (Panel) using ASP.NET instead.Alvin ChooiMicrosoft ASP.NET™ Enthusiast v1.1...

Client validation using both Javascript and .NET controls
 Hello,I have implemented an online questionnaire. The questionnaire is composed by several textboxes to gather information such as name, organization,email, phone, etc. and a long series of radiobuttonlists and textboxes (text area). These last textboxes need to be filled out only if the user select a specific value in the radiobuttonlists.To perform client validation I used .NET controls to check the format of the first textboxes (name, organization,email, phone, etc. ) and the text areas to ensure that no invalid characters have been entered.To check the all the radiobuttonlist has b...

Client side enable disable radio button list
Hi All I'm trying to enable / disable every item in a radiobuttonlist, depending on other user input. This needs to be done client side, using javascript. I've tried looping through each radio button (using ClientID property to ensure that the ID's are correct - and double checked against the source). This is not working, and the reason for this (when I view the source) is that the control is wrapped in a span tag (default for the radiobuttonlist is disabled), and the span tag is set to disabled. This tag has no ID, but forces the items to remain disabled no matter what i set each ...

How enable / disable linkbutton with checkbox client side javascript?
On the client, I want to enable a linkbutton if the user clicks a checkbox. If the user unchecks the checkbox, the linkbutton should become disabled. They should be able to toggle it back and forth. Is this possible? If so, how? By the way, I tried to test this in a separate page with pure HTML / Javascript and the anchor didn't appear in the form's elements when I used a for loop to list them out. Help! Thanks in advance. That is because a hyperlink isn't a form input element. In asp.net, the linkbutton is designed to behave like in input control, but it is in fact just an anchor w...

Need suggestions on client side control enabling/disabling
I want to enable checkboxes, textboxes, and requiredfieldvalidators on a checkbox click. I have everything working correctly using AJAX updatepanels and I think it works nicely... But what I think is not what is important. During testing, my client decided that the lag for the controls to be enabled (almost 2 seconds) is too long. I was doing all of the enabling/disabling on the server. I have tried to change this to all client using javascript, but the ASP.NET client side validation controls don't work well when you enable/disable them with javascript. What should I do to enabl...

How to conditionally Enable/Disable Button control using JavaScript ?
hi all... i have a Button control & a TextBox control on my web page. The Button control is initially Disabled. I want that while typing into TextBox, when the length of the contents of TextBox reaches to 12 (i.e. when i type 12th character), the Button Control should be Enabled & if the length again comes down to less than 12, the Button control should again be Disabled... How can i do this using JavaScript...?? Does anyone know how to do this...?? Please help. It's urgent... Thanx in advance to all posts !Sincerely,- Abhijeet Hi There, Base...

How to use client-side script(javascript) in .Net Remoting
Hi all,     It was known that SAO and Singleton object about .Net Remoting. When I Create an object in server side and hosting in IIS's virtual directory,I want to use javascript asynchronous invoking the remote object by HTTP channel, 80 port and SOAP formatter just like XMLHTTP invoking web service. My code as following, <script>  objXmlDoc = new ActiveXObject("Msxml2.DOMDocument"); objHttp = new ActiveXObject("Msxml2.XMLHTTP"); strEnvelope = ?? objHttp.onreadystatechange = function() { ......  }    szUrl = &...

Disabling a TextBox web control using javascript (client-side)
I'm using two textboxes and one button for a C# .NET web app code: <form id="Form1" method="post" runat="server"> <asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 248px; POSITION: absolute; TOP: 128px" runat="server"></asp:TextBox> <asp:TextBox id="TextBox2" style="Z-INDEX: 102; LEFT: 248px; POSITION: absolute; TOP: 168px" runat="server"></asp:TextBox> <asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 248px; POSITION: absolute; TO...

powerupasp.net treeview control & client-side population
Anybody ever used this treeview control? I'm using it in some custom modules and I'd like to use its client-side population of nodes ability, like on the msdn site. The treeview control uses a javascript xmlhttp object to callback to an aspx page to get the data to fill the opened node, but of course in dnn, the modules that contain the actual treeview are dynamically loaded, so it won't naturally work. Also, I would want the out of band request from the xmlhttp object to get authorized just like any regular request to a dnn site from a browser. Any ideas on how to implement this? Core ...

Web resources about - Correctly Enabling/Disabling an ASP.Net Button Control via Javascript - asp.net.client-side

JavaScript Kit- Your comprehensive JavaScript, DHTML, CSS, and Ajax stop
Your comprehensive JavaScript, DHTML, CSS, and Ajax stop

Let's Code: Test-Driven Javascript by James Shore — Kickstarter
James Shore is raising funds for Let's Code: Test-Driven Javascript on Kickstarter! A screencast series focusing on rigorous, professional Javascript ...

Eloquent JavaScript: A Modern Introduction to Programming
... and pragmatics. I loved the tutorial-style game-like program development. This book rekindled my earliest joys of programming. Plus, JavaScript! ...

Lightbox (JavaScript) - Wikipedia, the free encyclopedia
On a Lightbox-enabled page, a user can click an image to have it magnified in a Lightbox window, which resizes itself according to the size of ...

Open Directory - Computers: Programming: Languages: JavaScript: Tools: Obfuscators
about dmoz - help Top : Computers : Programming : Languages : JavaScript : Tools : Obfuscators Tools for obfuscation/compression JavaScript code. ...

Facebook Open-Sources JavaScript Static-Type Checker Flow
The latest software to be open-sourced by Facebook is Flow , a static-type checker for JavaScript . (more…) New Career Opportunities Daily: ...

Under the Hood: The JavaScript SDK - The use of polyfills - Facebook
Facebook Engineering hat eine Notiz mit dem Titel Under the Hood: The JavaScript SDK - The use of polyfills geschrieben. Du kannst den vollständigen ...

Quickstart: Facebook SDK for JavaScript
This quickstart will show you how to setup the SDK, load social plugins, trigger a dialog, and get it to make some basic Graph API calls.

Facebook App Devs Get Javascript
It has been an oft-lamented fact of the Facebook Platform thus far in its life that, in order to use all but the most simple of Javascript functionality–the ...

Badass JavaScript (@badass_js) on Twitter
WebGLWorker is an open source library that allows using WebGL from Web Workers. Great work as always from @kripken . blog.mozilla.org/research/2014/… ...

Resources last updated: 2/12/2016 5:12:31 PM