Disabled asp.net button disables validation for button - asp.net

I have an aspx page that contains a checkbox, and a button. The button is disabled by default until the user checks the checkbox. It looks like when I add the attribute enabled="false" to the button, it removes the validation. When the button is enabled, I still want the validation to work. Here is the code and markup for the different parts.
Checkbox:
<asp:CheckBox runat="server" ID="termsCheckBox" />
<label style="display: inline;">
I agree to the Terms & Conditions</label>
Button:
<asp:Button runat="server" ID="registerButton" OnClick="registerButton_Click1"
Text="Register" Enabled="false" ValidationGroup="accountValidation" />
JQuery:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#<%=termsCheckBox.ClientID %>').click(function () {
var checked = $(this).val();
if (checked != undefined)
$('#<%=registerButton.ClientID %>').removeAttr('disabled');
else
$('#<%=registerButton.ClientID %>').attr('disabled', 'disabled');
});
});
</script>

It seems like the validation should be attached to the checkbox, not the button.

Asp.net is stupid because when a control is disabled, there's all sorts of stuff that won't happen with it.
In this case, the js code to cause client side validation will not be created for a disabled button.
If you try to manually add in the clientside js code from the code behind,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
registerButton.OnClientClick = String.Format("javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('{0}', '', true, '', '', false, false))", registerButton.UniqueID)
End Sub
It will not work because asp.net will not render all the attributes for a disabled control.
There are two solutions then. Either disable the control with JS at client side or add the javascript to perform a postback with validation at client side.
What I did for my program was to add code to create js code to disable the button at the client side:
If btnSubmit.Enabled = False Then
'Asp.net will not render all the attributes for a control that is disabled. Even if you
'try to set the OnClientClick attribute manually in code behind for the control, it will
'not work. Asp.net will not render the attribute. This is a workaround for this problem.
btnSubmit.Enabled = True
strJavaScript &= "btnSubmit.disabled = true;"
End If
ClientScript.RegisterStartupScript(Page.GetType(), "myStartupScript", strJavaScript, True)
Note that btnSubmit is a javascript variable that is already defined in my client side code.

I think it would work if you enabled/disabled the button on the checkBox server-side event rather than client side since the associated client-side validation code will be generated to run for ValidationGroup of the button

Related

Control in UpdatePanel not found using $find

I have a complicated page but I created a simple ASP.NET page with the issue. I have telerik RadAsyncUpload control and a button inside an UpdatePanel as shown:
<asp:UpdatePanel ID="_updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
<telerik:RadAsyncUpload ID="fileUpload" runat="server" MaxFileInputsCount="1" OnClientFilesSelected="fileUpload_ClientFilesSelected" /><br />
<asp:Button ID="_saveNewFileButton" runat="server" OnClick="_saveNewFileButton_Click"
Text="Save"/>
</ContentTemplate>
</asp:UpdatePanel>
When a file is selected I want to disable the _saveNewFileButton and change the text to "Please Wait for Attachment Upload..." but I can't seem to get hold of the button reference in javascript:
var FilesUpdateInterval = null;
//Handles client side FilesSelected event for _newFileUploadButton.
function fileUpload_ClientFilesSelected(sender, args) {
//disable the click event for submit button during upload
var submitButton = $find('<%= _saveNewFileButton.ClientID %>');
submitButton.set_text('Please Wait for Attachment Upload...')
submitButton.set_readOnly(true);
if (FilesUpdateInterval == null) {
FilesUpdateInterval = setInterval(function () { FileCheckForUploadCompletion(); }, 500);
}
}
I am getting submitButton is null error. I tried putting this javascript code outside the updatepanel and inside ContentTemplate with same result. Obviously whatever I am doing is wrong. How do I get hold of the control that is in updatepanel in javascript?
EDIT: I find out that $find works with only telerik controls. So, I have to either use document.getElementById function or JQuery with something like Steve specified. Also, I have to use RegisterClientScriptBlock. I will test with Steve suggestion and then accept the answer.
short version - use $get() or document.getElementById(), as regular HTML elements are not IScriptControls, so $find() will not give you anything, and they don't have the rich client API you are trying to use.
For example
var submitButton = $get('<%= _saveNewFileButton.ClientID %>');
submitButton.setAttribute("value", "Please Wait for Attachment Upload...");
Option 2 - use RadButton.
Using jQuery and vb with ASP.Net, I've done something similar to this, which has worked well, even if it isn't that pretty. The [Whatever] I have was a FormView that didn't always have the control. Also, I didn't use it with a button, but I think that's the syntax for changing the button text. Either way, it might give you some ideas:
$('#<%=GetButtonClientID("_saveNewFileButton")%>').attr('value', 'Please Wait for Attachment Upload...');
And then I have a function like this:
Public Function GetButtonClientID(ByVal argFieldName As String) As String
Dim tmpID As String = "0"
Dim tmpButton As Button = [Whatever].FindControl(argFieldName)
If Not tmpButton Is Nothing Then Return tmpButton.ClientID.ToString Else Return "0"
End Function

How to display model popup at first time page load only

I used the following code to display model popup for the first time page load,
<script type="text/javascript">
function pageload() {
var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';
if (chkPostBack == 'false') {
var popup = $find('ModalPopupExtender1');
if (popup != null) {
popup.show();
}
}
}
I got the following error, Please help me.
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
I would suggest to show the ModalPopup from codebehind if(!Page.IsPostBack). Therefore you can use the Show method of ModalPopupExtender.
if(!Page.IsPostBack)
{
ModalPopupExtender1.Show();
}
To enable it to be opened from serverside, you need to set the TargetControlID of the ModalPopupExtender to a hidden button:
<asp:Button ID="Hid_ShowDialog" Style="display: none" runat="server" />
I would suggest performing this code from the .net code then you can do a isPostBack check, or even if you only want it once for an entire session then once you've run the JS from the .net code, set Session("ShowPopup") to false and then check against that.
Though for this problem try changing the code block to start with:
<%# instead of <%=

Validation based on visibility of a label

I like to add a validation on a label based on its visibility, in that a submit button will raise a validation message or error if the label is not visible.
I am used to the validation controls in the Toolbox, which wont allow this functionality!
It seems as though if an asp:Label's visibility is set to false, the asp.net engine will not even put it in the DOM. So you can check in javascript, using the onclick property of the (html) button to check if the label is in the DOM or not, and use asp.net's __doPostBack() javascript function to post back to the server if it is there:
<script type="text/javascript">
function testMe()
{
var lbl = document.getElementById('lblTest');
if(lbl == null)
document.getElementById('msg').innerHTML = "Error";
else
__doPostBack('testButton');
}
</script>
<asp:Label ID="lblTest" runat="server" Visible="false" Text="Hello"></asp:Label>
<button onclick="testMe();">test</button>
To be completely honest, I thought the lbl would be undefined if the label did not exist in the DOM, but Firebug revealed it is actually null. Anyway, a couple things to note is that in order for asp.net to define the __doPostBack() method, I believe you need some control in the form that has autopostback="true", and in the code-behind you can check what caused the postback in the Page_Load method like so:
if(Request.Form["__EVENTTARGET"] == "testButton") {}

Handle two events on button click

I am a bit new to the asp.net/jQuery game, and I seem to be having difficulty. I am using colorbox to make a modal window popup, and I want an upload picture form on that modal window. I have a button to open up the add photo form:
Add/Edit picture(s)<br />
<script>
$(document).ready(function () {
$(".addpicture").colorbox({ width: "50%", inline: true, href: "#page1" });
});
</script>
Thus far my modal window is working perfectly, and is displaying the following upload form and next button:
<asp:FileUpload ID="picup" runat="server" class="upload" /><br />
<asp:Button ID="Button1" type="button" runat="server" Text="Next Page" class="nextpage" />
Here's where I am stuck; I am trying to have the next button upload the picture, and move to a second modal window, which I am going to implement a crop function on. The problem is, to do this, I need a jquery event handler:
$(".nextpage").colorbox({ width: "50%", inline: true, href: "#page2" });
I also need a serverside event handler to do the actual upload:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
picup.PostedFile.SaveAs("\Pictures\1-a.jpg")
Catch ex As Exception
Response.Write("Upload Failed")
End Try
End Sub
However, when I put in a breakpoint, this event handler is never firing.
A possible solution I thought up is to make a hidden button that fires the javascript, and click that button from vb, but I couldn't figure out how to click a button from vb. Is there something I'm doing fundamentally wrong? Is there a good way to accomplish what I want?
Edit: I have changed the way I am doing this, instead of multiple modal windows, I am loading a separate page in an iframe on the modal window, then I can have a postback without reloading the main page. Thank you for your help.
When uploading files with the fileUpload control you need a postback, otherwise the event will never fire.
There are a couple of plugins por jQuery that promise to enable uploading via ajax but i've never tried any.
In jquery bind() method lets you attach different behaviors to an element :
Example:
$("#a").bind("mouseover mouseout", function(e){
$(this).text($(this).text() + " event triggered " );
});

Disable a button on click

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;

Resources