I hava an ASP.NET Web Forms application.
My goal is to disable the submit button btnFinish
upon user click, in order to avoid multiple submits.
<asp:Button ID="btnFinish" runat="server" Text="Finish" UseSubmitBehavior="false"
CausesValidation="true" CommandName="MoveComplete" CssClass="buttonStyle"/>
The Javascript function is:
function Validate(btnFinishId) {
btnObj = document.getElementById(btnFinishId)
if (Page_IsValid) {
btnObj.disabled = true
}
else {
alert('Page has some validation error');
}
// this is to prevent the actual submit
e.preventDefault();
return false;
};
btnFinish
is placed within a FinishNavigationTemplate
in a ASP.NET Wizard Control. Therefore, in order to avoid runtime errors, I need to get the ClientID
of the control programmatically and then add it to the OnClientClick
event of the button:
Button btFinish = MyWizard.FindControl("FinishNavigationTemplateContainerID$btnFinish") as Button;
if (btFinish != null){
btFinish.Attributes.Add("onclientclick", "Validate('" + btFinish.ClientID + "');");
}
But it does not work. I use Firebug to check the page rendered by the browser but although the source code looks perfect, upon click the Javascript function is not executed .
If in the Javascript function I replace Validate(btnFinishId)
with Validate()
and instead of using the code behind to add the OnClientClick
I write:
<asp:Button OnClientClick="Validate();" "ID="btnFinish" runat="server" Text="Finish" UseSubmitBehavior="false"
CausesValidation="true" CommandName="MoveComplete" CssClass="buttonStyle"/>
The function is executed but of course does not do what I want, because the button Id is missing. Anybody has a solution?
You're on the right track. Something like this should work:
<script type="text/javascript">
validate = function(btn){
//trigger client-side validation
var valid = Page_ClientValidate("");
//disable the button if the form is valid
btn.disabled = valid;
//trigger postback if the form is valid
//otherwise do nothing
return valid;
}
</script>
<asp:Button ID="btnFinish" runat="server" Text="Finish" OnClientClick="return validate(this);" OnClick="btnFinish_Click" ... />
It looks kind of backwards, but you could shorten the function like this:
<script type="text/javascript">
validate = function(btn){
btn.disabled = Page_ClientValidate("");
return btn.disabled;
}
</script>
One way is to create a normal HTML button on your page, add attach a click event with jQuery. You can then hide the .net button using css.
In the click event for your html buttom, you can all the .net buttons click event.
$("#yourbutton").trigger("click");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.