Disable a button on click - asp.net

I have a button control. Once the user clicks on it, the click event should fire and then the button should get disabled. How can I do this? I have the option to use JQuery or JavaScript or both.
Here is my button declaration:
<asp:Button
ID="Button1"
runat="server"
Text="Click Me"
onclick="Button1_Click"
/>
On the button click code behind, I have added a Response.Write(). That should get executed and then the button should be disabled

For whatever reason, the HTML spec dictates that disabled elements should not be included in POST requests. So, if you use JavaScript to disable the HTML element in the client-side onclick event, the input element will be disabled when the browser assembles the POST request, the server won't be properly notified which element raised the postback, and it won't fire server-side click event handlers.
When you set the UseSubmitBehavior property to false, ASP.NET renders an input element of type button instead of the regular input of type submit that the ASP.NET Button control normally generates. This is important because clicking a button element does not trigger the browser's form submit event.
Instead of relying on a browser form submission, ASP.NET will render a client-side call to __doPostBack() within that button element's onclick handler. __doPostBack will raise the postback explicitly, regardless of what POST data comes through in the request.
With the postback being raised independent of the browser submit event, you're freed of the previously mentioned HTML quirk. Then, you can set an OnClientClick of "this.disabled = true;", which will render as "this.disabled = true; __doPostBack('Button1', '');", and things will work as intended.

add an OnClientClick="this.disabled = true;" to your button.
If you are using Asp.net Ajax you might want to look at using PostBack Ritalin.

Have you tried this?
Add an OnClientClick="MyFunction();" to your .NET button.
Then in the .aspx page script tags you add the following JS function:
<script type="text/javascript">
function MyFunction()
{
window.setTimeout(function ()
{
// get the button/control to disable using your favourite clientside ...
// ... control grabbing code snippet ...
// ... eg. JQUERY $('Button1'), getElementById, etc.)
document.getElementsByName('Button1').Button1.disabled = true;
// I've used "getElementsByName" because .NET will render a button with
// ... a "name" attribute, and not an "id" attribute, by default
}, 1);
}
</script>
This gives the browser a chance to post back, followed by a quick button disable.

You need to be careful that the postback occurs before you disable the button through client script. This is a common gotcha with ajax and input boxes. Disabling an input box prevents the data from being sent from the browser, even if you can see text within it while it is disabled. The answer is that you need to use jquery for this to ensure the server-side code runs first before it is disabled.
-Oisin

// to disable
this.setAttribute('disabled', true);
// to enable
this.removeAttribute('disabled');
this is a cross browser solution

There is really cool event for body tag "<"body onBeforeunload="buttonId.disabled = true;" ">"
This event triggers right before form submits, in other words your data will be submitted correctly.

When using the "this.disabled = true" method make sure you check if the page is valid before disabling the control if you have validators on the page. If validation fails you won't be able to re-enable the control without reloading the page.
if (Page_IsValid) this.disabled = true;

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) {
document.getElementById('<%= lblMessage.ClientID %>').innerText = "Processing...";
document.getElementById('<%= btnSubmit.ClientID %>').innerText = "Processing";
args.get_postBackElement().disabled = true;
}
</script>
Add Script Tag in source page . change Id of button in code . You can disable the button till the process completes execution .

you can disable it server side
Button1.Enabled = false;

Related

What does aspnet keep overwritting my onclick attribute?

I have a button on the form. During Page_Load event I add a new onclick attribute to the button via code behind. However when I inspect the button in firefox my attribute is not there and is being replaced with:
onclick='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("button_modal_search", "", true, "modalSearch", "", false, false))'
here is the tag before I run the app:
here's my code behind:
button_modal_search.Attributes.Add("onclick", "return showSearchSpinner()")
Anyone know how I can prevent the attribute from being overwritten?
ASP.NET indeed overrides your onclick attribute, but does provide the OnClientClick property to allow you to specify your own client-side behavior:
button_modal_search.OnClientClick = "return showSearchSpinner();"
If the value of that property is constant, you can also specify it as an attribute in the button markup itself.
There is a property OnClientClick: button_modal_search.OnClientClick="return showSearchSpinner();"
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick%28v=vs.110%29.aspx
button_modal_search.Attributes.Add("onclick", "return
showSearchSpinner()")
Above code is ok. If you do not want to postback to server, you just need to return false from javascript function.
Otherwise, it'll post back to server after running the showSearchSpinner function.
function showSearchSpinner(){
// do something
return false;
}
Note: You do not need to worry about ASP.Net replacing onclick event - onclick='javascript:WebForm_... false, false))'.
Basically showSearchSpinner javascript function intercepts ASP.Net click event, when you click on button_modal_search button.

ASP.NET TextBox's OnTextChanged server event should fire some client code before going to server

My UserControl has a TextBox, that is subscribed to OnTextChanged event. However, since a lots of business logic and integrations happens on server, I want to disable a form while postback is being performed with some client-side javascript and I'm not sure how to achieve it the right way.
Can I solve this with ClientScriptManager.GetPostBackEventReference?
Edit: as my question seems to be misunderstood:
TextBox is subscribed to event OnTextChanged="tb_TextChanged" which will result on client in onchange=__doPostBack('tb') so I want to inject my javascript disableForm() to onchange DOM event. I know how to implement disableForm(), the question is how to inject my javascript properly?
I would suggest you use the javascript onblur event and check if the field value is changed. If so, you can use jQuery like the below to disable the form elements.
To disable a form element such as a text input or a button (with a made-up id: #elm):
$("#elm").attr("disabled", "disabled");
To enable a disabled form element:
$("#elm").removeAttr("disabled");
You should be able to do this with some simple JavaScript:
<script type="text/javascript">
disableFormFields = function(){
if (document.all || document.getElementById){
for (i = 0; i < document.forms[0].elements.length; i++){
var el = document.forms[0].elements[i];
if (el){
el.disabled = true;
}
}
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server" onchange="disableFormFields();" OnTextChanged="TextBox1_TextChanged" />

Response.End doesnot render javascript

On the click of the button my Onclick event gets fired.
Inside the onclick event I generate somefile at runtime and render it to the browser in the following way. But before rendering it to the browser I am making particular Label visible. But still the Label never become visible. Any idea what is the problem
lblInfoMessage.Visible=true;
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=test.gxml");
doc.Save(Response.OutputStream);
Response.End();
You can either refresh the page (and thus change visibility or contents of controls) or send an attachment. Not both. So you will have to find some other way, maybe client side javascript?
EDIT
In the button you need a OnClientClick in the server side code, this will translate into a client-side "onclick". Here you can call a javascript function where you can (for instance) display some text. Note that this function is executed before the submit action that will generate the file.
Something like this in the html/aspx:
<span id="infoMessage"><!-- empty --></span>
...
<asp:Button OnClientClick="showInfo()" ... />
...
<script type="text/javascript">
function showInfo() {
document.getElementById("infoMessage").innerText =
"This is the info message.";
}
</script>
You can't just show that Label that you have now, as that doesn't exist in the client-side html when it is invisible.
should it not be as below?
lblInfoMessage.Visible=true;

LinkButton does not invoke on click()

Why doesn't this work?
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.myButton').click();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton id="ttt" runat="server" PostBackUrl="~/Default.aspx" CssClass="myButton">Click</asp:LinkButton>
</div>
</form>
Do you want to submit the form, or add a Click event?
Your link button translates to
<a id="ttt" class="myButton" href="javascript:WebForm_DoPos[...]">Click</a>
, so it has no on-click javascript. Therefore, .click(); does nothing.
I haven't test it, but maybe this will work:
eval($('.myButton').attr('href'));
trigger('click') fires jQuery's click event listener which .NET isn't hooked up to. You can just fire the javascript click event which will go to (or run in this case) what is in the href attribute:
$('.myButton')[0].click();
or
($('.myButton').length ? $('.myButton') : $('<a/>'))[0].click();
If your not sure that the button is going to be present on the page.
Joe
If you need the linkbutton's OnClick server-side event to fire, you need to use __doPostback(eventTarget, eventArgument).
ex:
<asp:LinkButton ID="btnMyButton" runat="Server" OnClick="Button_Click" />
<script type="text/javascript">
function onMyClientClick(){
//do some client side stuff
//'click' the link button, form will post, Button_Click will fire on back-end
//that's two underscores
__doPostBack('<%=btnMyButton.UniqueID%>', ''); //the second parameter is required and superfluous, just use blank
}
</script>
you need to assign an event handler to fire for when the click event is raised
$(document).ready(function() {
$('.myButton', '#form1')
.click(function() {
/*
Your code to run when Click event is raised.
In this case, something like window.location = "http://..."
This can be an anonymous or named function
*/
return false; // This is required as you have set a PostbackUrl
// on the LinkButton which will post the form
// to the specified URL
});
});
I have tested the above with ASP.NET 3.5 and it works as expected.
There is also the OnClientClick attribute on the Linkbutton, which specifies client side script to run when the click event is raised.
Can I ask what you are trying to achieve?
The click event handler has to actually perform an action. Try this:
$(function () {
$('.myButton').click(function () { alert('Hello!'); });
});
you need to give the linkButton a CssClass="myButton" then use this in the top
$(document).ready(function() {
$('.myButton').click(function(){
alert("hello thar");
});
});
That's a tough one. As I understand it, you want to mimic the behavior of clicking the button in javascript code. The problem is that ASP.NET adds some fancy javascript code to the onclick handler.
When manually firing an event in jQuery, only the event code added by jQuery will be executed, not the javascript in the onclick attribute or the href attribute. So the idea is to create a new event handler that will execute the original javascript defined in attributes.
What I'm going to propose hasn't been tested, but I'll give it a shot:
$(document).ready(function() {
// redefine the event
$(".myButton").click(function() {
var href = $(this).attr("href");
if (href.substr(0,10) == "javascript:") {
new Function(href.substr(10)).call(this);
// this will make sure that "this" is
// correctly set when evaluating the javascript
// code
} else {
window.location = href;
}
return false;
});
// this will fire the click:
$(".myButton").click();
});
Just to clarify, only FireFox suffers from this issue. See http://www.devtoolshed.com/content/fix-firefox-click-event-issue. In FireFox, anchor (a) tags have no click() function to allow JavaScript code to directly simulate click events on them. They do allow you to map the click event of the anchor tag, just not to simulate it with the click() function.
Fortunately, ASP.NET puts the JavaScript postback code into the href attribute, where you can get it and run eval on it. (Or just call window.location.href = document.GetElementById('LinkButton1').href;).
Alternatively, you could just call __doPostBack('LinkButton1'); note that 'LinkButton1' should be replaced by the ClientID/UniqueID of the LinkButton to handle naming containers, e.g. UserControls, MasterPages, etc.
Jordan Rieger

AutoPostback with TextBox loses focus

A TextBox is set to AutoPostback as changing the value should cause a number of (display-only) fields to be recalculated and displayed.
That works fine.
However, when the field is tabbed out of, the focus briefly moves on to the next field, then disappears when the page is redrawn so there is no focus anywhere.
I want the focus to be on the new field, not the textbox I've just changed.
Is there a way to work out which field had the focus and force it to have it again when the page is redrawn?
This is "by design". If you are using ASP.NET 2.0+ you can try calling the Focus method of your TextBox once the postback occurs (preferably in the TextChanged event of the TextBox).
I am not sure if there is any built-in way to track focus but I found this article in CodeProject which should do the trick.
You could also consider refresh display-only fields using AJAX UpdatePanel. This way you won't lose focus from the new field.
Also I have proposed pure server-side solution based on WebControl.Controls.TabIndex analysis, you can use it, if you like.
This is what is happening:
1) TAB on a field - client event
2) Focus on next field - client event
3) Postback - server event
4) Page redrawn - client event new page overrides preious client events
The solution of your problem is to:
a) get the element that has gained focus BEFORE postback
<script>
var idSelected;
$("input").focusin(function () {
idSelected = this.id;
});
</script>
b) store the ClientID (actually in var idSelected) somewhere (i.e. an hidden Textbox, vith ViewState = true) BEFORE postback
** b) get ClientID ** (extract from hidden TextBox and put it in var idSelected) AFTER postback
d) get the element with ClientID and set focus AFTER postback
<script>
$(document).ready(function () {
if (idSelected != null) {
$("#" + idSelected).focus();
idSelected = null;
});
});
</script>
Note: this sample scripts use JQuery.
Remember to put Jquery.js in your solution and a reference in your page
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<asp:ScriptManager runat="server" >
<Scripts>
<asp:ScriptReference Path="~/Scripts/jquery.js" ScriptMode="Auto" />
....
Note2: this solution works without AJAX.
Look at this answer: to make Javascript work over Ajax you must use code like this:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args)
{
MyScript();
}
</script>

Resources