When I am Clicking on button of asp.net then on client click I am disabling that clicked button then server side click event is not firing.
My code is as following:
<asp:Button ID="ButtonSend2" runat="server" CssClass="CommonButtonStyle" Text="Send Message" OnClientClick="this.disabled='true';return OnClickSendEmail();"
OnClick="btnSend_Click" ValidationGroup="ValidationGroupCompose" />
and This is my Java script code:
function OnClickSendEmail() {
var value = document.getElementById('CE_ctl00_ContentMain_TextArea_ID').getHTML().replace(/ /g, "").trim();
if (value == "" || value == undefined) {
$j('#ctl00_ContentMain_lblMessage').text('Message body can\'t be blank!');
$j('#ctl00_ContentMain_lblMessage').show()
return false;
} else {
$j('#ctl00_ContentMain_lblMessage').text('');
console.log("Value is returing true");
return true;
}
}
Once the button is disabled, the postback is not made. You could re-enable the button at the end of the processing but there is another problem: the display will not be updated when the browser is busy processing OnClickSendEmail(), so the button will never look disabled.
Here is a possible solution, which involves canceling the postback at first and processing the command asynchronously:
<asp:Button ID="ButtonSend2" runat="server" OnClientClick="this.disabled = true; setTimeout(OnClickSendEmail, 0); return false;" ... />
The postback is then triggered with __doPostBack at the end of the lengthy processing:
function OnClickSendEmail() {
var value = document.getElementById('CE_ctl00_ContentMain_TextArea_ID').getHTML().replace(/ /g, "").trim();
if (value == "" || value == undefined) {
$j('#ctl00_ContentMain_lblMessage').text('Message body can\'t be blank!');
$j('#ctl00_ContentMain_lblMessage').show()
} else {
$j('#ctl00_ContentMain_lblMessage').text('');
console.log("Value is returing true");
__doPostBack('<%= ButtonSend2.UniqueID %>', '');
}
}
On your javascript code, there are two points that can cause not firing at the end. I write on the code the possible points. Also you have include it on ValidationGroupCompose validation, are you sure that is not stopped from there ?
function OnClickSendEmail() {
// !!! if the element not found is throw an error here and not continue at all.
var value = document.getElementById('CE_ctl00_ContentMain_TextArea_ID').getHTML().replace(/ /g, "").trim();
if (value == "" || value == undefined) {
$j('#ctl00_ContentMain_lblMessage').text('Message body can\'t be blank!');
$j('#ctl00_ContentMain_lblMessage').show()
// !!!! if comes here and return false, then is NOT firing, not continue.
return false;
} else {
$j('#ctl00_ContentMain_lblMessage').text('');
// !!!! if comes here and you not use a browser that support the console, function, is thrown an error and not continue to fire up.
console.log("Value is returing true");
return true;
}
}
Debug your javascript to see whats going wrong, also remove the console.log from your final code.
Related
I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.
Coding in VS-2012 Express for Web , WebForms, Ajax -- VB.Net.
I want to prevent the user from leaving the page when button-click starts a long server process. This works perfectly the first time clicking 'cmdDoMonthlyReports' button and letting the process complete to show the results in a [span] element. But if I click the button a second time, the [span] innerHTML are NOT cleared from the page -- but the process runs again (as expected) with the old results showing in the [span] during the process execution -- which is NOT correct.
The problem is the [span] is NOT cleared when 'SetIsBusy()' js-function is run, because the element oSpan is always null
var oSpan = document.getElementById('< %= idSpanResult.ClientID%>');
returns as null and thus the innerHTML does not get cleared.
My question is "why" does the oSpan element always null?
Any comments or solutions will be greatly appreciated...thanks.
Here is my markup for the asp.button.
<asp:Button ID="cmdDoMonthlyReports" runat="server" Text="Do Monthly Reports" SkinID="cmdButton" OnClientClick="SetIsBusy(true)"/>
Here is the javascript for the ClientClick -- calling 'SetIsBusy(true)'...
var m_bIsBusy = false;
window.onbeforeunload = confirmExit;
function confirmExit() {
var oCtrl = document.getElementById('<%= idIsBusy.ClientID%>');
//if (oCtrl != null) { m_bIsBusy = (oCtrl.value.toLowerCase() === "true") } else { m_bIsBusy = false; }
m_bIsBusy = (oCtrl != null) ? (oCtrl.value.toLowerCase() === "true") : false;
if (m_bIsBusy) {
return "You have attempted to leave this page. If you leave this page, now, you will lose all of your generated monthly reports. Are you sure you want to leave this page?";
}
}
function SetIsBusy(p_IsBusy) {
m_bIsBusy = p_IsBusy;
if (m_bIsBusy == true) {
var oSpan = document.getElementById('< %= idSpanResult.ClientID%>');
if (oSpan == null) { oSpan = document.getElementById('idSpanResult'); }
if (oSpan != null) { oSpan.innerHTML = ''; }
}
}
The button.click also fires on the server in the code-behind where some validations take place and then the long-running process executes. The results of the process are contained in a text-string which updates to the response back to the browser. Here is that code-behind code.
Protected Sub cmdDoMonthlyReports_Click(sender As Object, e As EventArgs) Handles cmdDoMonthlyReports.Click
...some validation code...
Call sbGenerateReports()
Dim sResultText As String = m_sResultsHTML
idSpanResult.InnerHtml = sResultText
idSpanResult.Visible = True
updpnlDetails.Update()
End Sub
At the bottom of my webpage, I have a submit button. I've used this code:
<a onClick="myFunction(); return false;" href="testpage.html">Submit</a>
What I'm trying to do is when my function is called, I'm checking for validation. If it's false, my function raises an alert and the user doesn't leave the current page...which is what I want. When its true though...nothing changes. When it's true I want them to go to the next link.
function myFunction() {
if (localStorage.length != 3) {
alert("Missing Values");
} else {
break;
}
}
It goes to the next link when I put in break, but now the alert doesn't get called even if it's requirements are met. Moreover, whey does the break in the else block get called even when the if block requirements are met?
Well return false cancels the action. So if you do not want to stop the link, you need to remove that.
<a onclick="return myFunction();" href="testpage.html">Submit</a>
Now return true or false from myFunction
function myFunction() {
if (localStorage.length != 3) {
alert("Missing Values");
return false;
}
return true;
}
Rewrite your html to <a onClick="myFunction()" href="testpage.html">Submit</a> and function to:
function myFunction() {
if (localStorage.length != 3) {
event.preventDefault();
}
}
See Fiddle: https://jsfiddle.net/ermakovnikolay/L0q7ocgg/
I have to resolve a problem in some code assigned to me and the problem is that following this code in page.init else statemant:
Me.SaveChangesButton.Attributes.Add("OnClick",
"if (!confirm('Are you sure?')){
return false;
} else {
document.getElementById('SaveChangesButton').disabled = true;
document.getElementById('rejectButton').disabled = true;
}
")
overrides this code:
Protected Sub SaveChangesButton_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles SaveChangesButton.Click
Question [edited]
How can I bind confirm() to button so that it doesn't override my handler function?
Where in the code would it be best practice to bind it?
If I remove second part else {document.getElementById('SaveChangesButton').disabled =
true; document.getElementById('rejectButton').disabled = true;} it works correctly, but how should I write it so it continues to execute SaveChangesButton_Click, as I understand only the second part overrides handler?
How can I execute those two lines document.getElementById('SaveChangesButton').disabled = true;
document.getElementById('rejectButton').disabled = true; and still execute SaveChangesButton_Click handler without overriding it?
1) You should use OnClientClick:
Me.SaveChangesButton.OnClientClick = #"
if (!confirm('Are you sure?')) {
return false;
} else {
document.getElementById('SaveChangesButton').disabled = true;
document.getElementById('rejectButton').disabled = true;
}"
2) If you bind the SaveChangesButton_Click in the Page.Init, I would then set the OnClientClick too.
3,4) The OnClientClick fires (sort of) before the server side OnClick (of course). This makes you disabling your button, before firing the OnClick. And OnClick won't fire on a disabled button. What to do? Delay disabling your button.
Me.SaveChangesButton.OnClientClick = #"
if (!confirm('Are you sure?')) {
return false;
} else {
setTimeout(function(){
document.getElementById('SaveChangesButton').disabled = true;
document.getElementById('rejectButton').disabled = true;
}, 100);
}"
And this actually makes your question a duplicate of this one...
Disable a post back from asp.net i.e. buttons, links, gridview page index changing and sorting etc when a post back is already in progress. Target browser is IE 6+. I've written these 2 javascript I am not sure how to apply it on GridView Page Index changing.
<script type="text/javascript">
//isFormSubmitted variable is used to prevent the form submission while the server execution is in progress
var isFormSubmitted = false;
//If the form is already submitted, this function will return false preventing the form submission again.
function SubmitForm(msg)
{
try {
if(isFormSubmitted == true)
{
alert('A post back is already in progress. Please wait');
return false;
}
else
{
var res = false;
if (msg)
{
res = confirm(msg);
}
if (res == true)
{
isFormSubmitted = true;
}
return res;
}
} catch(ex) {}
}
function VerifySubmit()
{
if(isFormSubmitted == true)
{
alert('A post back is already in progress. Please wait');
return false;
}
else
{
isFormSubmitted = true;
return true;
}
}
</script>
For buttons I can attach the SubmitForm to OnClientClick like this.
<asp:Button ID="btnCancel" runat="server" CssClass="button" Text="Cancel" OnClick="btnCancel_Click" OnClientClick="return SubmitForm('Do you want to continue with cancelling recent action?');" />
But I am not sure how to attach the VerifySubmit to non prompting controls like gridview pager.
onclick="this.disabled=true;"
on your submit-button(s) is all the javascript "magic" you need
When jQuery is an option you can use this small script to disable all submit-buttons:
// Find ALL <form> tags on your page
$('form').submit(function(){
// On submit disable its submit button
$('input[type=submit]', this).attr('disabled', 'disabled');
});
Found here: http://jquery-howto.blogspot.com/2009/05/disable-submit-button-on-form-submit.html
Or you can block the whole page: http://jquery.malsup.com/block/#page
If you want to disable post back set autopastback=false for buttons links.
Otherwise you need to give us more information and better instructions / details to help you out.
I'm going to guess that you're doing ajaxy type stuff here and you have an async-postback going and you don't want the user to click a button at that time.
If that is the case then try the following code:
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(startRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
function startRequest(sender, e) {
//disable search button during the AJAX call
document.getElementById('<%=btnSearch.ClientID%>').disabled = true;
}
function endRequest(sender, e) {
//re-enable the search button once the AJAX call has completed
document.getElementById('<%=btnSearch.ClientID%>').disabled = false;
}
The easiest solution I found is that..
//In the head section define this script...
<script type="text/javascript">
function ShowProcessingMsg(confirmMsg) {
var resp = confrim(confirmMsg);
try {
if (resp == true) {
var divC = document.getElementById('<%= divControls.ClientID %>');
var divM = document.getElementById('<%= divProcessingMsg.ClientID %>');
if (divC && divM) {
divC.display = "none";
divM.display = "block";
}
else {
return false;
}
}
} catch (exp) { alert(exp); return false; }
return resp;
}
</script>
//This div will show during processing since by default it's display is none when after
//Post back your page loaded again this will not be diplayed. We are going to set it's
//diplay attribute to block from javascript.
<div id="divProcessingMsg" runat="server" display="none" z-index="1000" />
<b>Processing.... Please wait.</b>
</div>
//We will hide this div from script by setting its display attribute to none. Since
//by default this attribute is block when the page loaded again it'll be displayed by
//default. So no special handling for setting display again to block is required.
<div id="divControls" runat="server" display="block" z-index="1" />
<asp:GridView ............ >
.....
.....
.....
<asp:Button runat="server" id="btnProcess" Text="Process" OnClientClick="return ShowProcessingMsg('Do you want to continue with processing'); OnClick="btnProcess_ServerClick" />
</div>