ASP.NET OnClick/OnClientClick - Broken if submit button disabled

1.3k Views Asked by At

I have known good working JS validation functions (validated all the way back to OnClientClick). When called by OnClientClick, they check whether all the required fields have been populated, disable the submit button, and return the correct true/false validation to OnClientClick.

The problem is in disabling the button. The page submits and reloads, but the OnClick event is not fired. Remarking the

document.getElementById("<%=btnSubmit.ClientID %>").disabled = true;

code allows the OnClick event to fire.

I have tried inserting

this.disabled=true;

directly into OnClientClick, as well as using UseSubmitBehavior=false.

Why does the OnClick event not fire when the button is disabled?

4

There are 4 best solutions below

0
Luongatoolz On

two things:

1 make sure 'disabled' attribute is not set. Try removing the attribute by

document.getElementById("<%=btnSubmit.ClientID %>").removeAttribute('disabled');

2 OnClick post back should be able to run if you call:

var button = document.getElementById("<%=btnSubmit.ClientID %>");
window.location.href = button.getAttribute("href");

basically it forces the browser to send the request as OnClick is server side method.

0
VDWWD On

You could just wrap the button with a div element containing the onClick event. That should fire even if the button itself is disabled. The only downside is that you cannot assign the event to the button directly from code-behind. From your question it looks like the onClick event should always fire, whether the button is enabled or not.

0
SlowCoder74 On

I used the following setTimeout() code to fix the problem, which I found here, in an answer posted by ConnorsFan.

function Control_Enable(controlId, enable) {
    setTimeout(function () {
        var ctrl = document.getElementById(controlId);
        ctrl.disabled = !enable;
    }, 10);
}
0
Дима Юхименко On

just for disabled fields add

@Html.HiddenFor(model => model.Id)

and the ViewModel will pick it up as intended