0
votes

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
If the button is disabled its normal that the OnClick function will not be executed...Mivaweb
You can use setTimeout to disable the button, as suggested in this post: stackoverflow.com/questions/37955604/….ConnorsFan
The solution provided by @ConnorsFan (using setTimeout) seems to have fixed my problem. I'm not sure why it should matter if the button is disabled AFTER clicking it. An explanation would be nice?SlowCoder74
The postback is made as soon as the button is clicked, and while it is still enabled. Once the data has been sent to the server, the button can be disabled without having any effect on the processing that is taking place on the server.ConnorsFan

4 Answers

0
votes

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
votes

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
votes

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
votes

just for disabled fields add

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

and the ViewModel will pick it up as intended