I am working on an ASP.NET web forms application in C#. I have a button that needs to run some client-side Javascript (using the OnClientClick attribute), then run server-side code (using OnClick) if the client-side code returns true. I've done this plenty of times before with jQuery-ui confirmation dialogs, however this time my client-side code isn't a confirmation dialog and it isn't working -- the server-side (OnClick) event never gets triggered even though I'm explicitly returning true.
Here's the client-side code in question, which is working (I've verified that it's returning the correct value with an alert() call):
<script type="text/javascript">
//Function to hide edit fields
function hideEditFields(retVal) {
//Hide all edit divs
var editName = document.getElementsByClassName("editField");
for (i = 0; i < editName.length; i++) {
editName[i].style.display = 'none';
}
//Show all view divs
var viewName = document.getElementsByClassName("viewField");
for (i = 0; i < viewName.length; i++) {
viewName[i].style.display = 'block';
}
//Make investigated & corrective action checkboxes non-highlighted
$('<%=cbInvestigatedY.ClientID%>').removeClass("editable");
$('<%=cbInvestigatedN.ClientID%>').removeClass("editable");
$('<%=cbCorrectiveY.ClientID%>').removeClass("editable");
$('<%=cbCorrectiveN.ClientID%>').removeClass("editable");
//Show edit button
var editButton = document.getElementById("editButton");
editButton.style.display = 'block';
//Hide save button
var saveButton = document.getElementById("saveButton");
saveButton.style.display = 'none';
//alert("returning " + retVal);
return retVal;
}
</script>
And here's the button that calls this function:
<asp:Button ID="btnSaveChanges" runat="server" OnClientClick="return
hideEditFields(true);" OnClick="btnSubmit_Click" Text="Save Changes" />
I've tried this with UseSubmitBehavior="true"
and without, which seems to make no difference. I'm getting no errors in the Javascript console, and the Javascript code is doing what it's supposed to do, it's just not calling the server-side method.
Here's how the submit button gets rendered (in view source) by ASP.NET:
<input type="submit" name="ctl00$MainContent$btnSaveChanges" value="Save Changes"
onclick="return hideEditFields(true);WebForm_DoPostBackWithOptions(new
WebForm_PostBackOptions("ctl00$MainContent$btnSaveChanges", "",
true, "", "", false, false))"
id="ctl00_MainContent_btnSaveChanges" />
asp:Button
is being rendered? Also, if you remove theonClientClick
attribute, does the server get called correctly? – Ianreturn
like you are, the rest of theonclick
won't execute, whether it's true or false. That's why - those .NET function calls don't set up the submit to behave correctly so the server can know the trigger – Ian