Disallowing POST BACK when one is already in progress - javascript

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>

Related

How do I disable an asp:CheckBox after it is checked and then execute server side code?

I have an asp.net checkbox, which looks like this:
<asp:CheckBox ID="chkDoSomething" runat="server" AutoPostBack="true" OnCheckedChanged="DoSomething" />
As expected when I check the checkbox; the DoSomething method is called on the server side. After the user has checked the checkbox; I want to disable it (so they cannot click it multiple times).
If I was using a button, then I could use OnClick and OnClientClick. How can I do this with a Checkbox?
I have spent one hour Googling this and have looked here for example: Enabling/disabling asp.net checkboxes through javascript
I cannot find an answer to my question. Most questions I have read assume that you want to execute Javascript only and not both Javascript and server side code.
Update 1
Here is the onchange method:
function Disable
Checkbox()
{
document.getElementById("chkDoSomething").disabled = true;
}
Update 2
I have tried this:
var chkDoSomething = document.getElementById("chkDoSomething");
if (chkDoSomething != null) {
chkDoSomething.addEventListener('change', function () {
chkDoSomething.disabled = true;
});
}
Still the Javascript blocks the post back. As soon as I remove the Javascript, then the postback works.
You can also disable the CheckBox in the CheckedChanged event.
protected void chkDoSomething_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = sender as CheckBox;
cb.Enabled = false;
}
Update
A client side solution would be to wrap the CheckBox in a div and add pointer-events:none to it.
<div>
<asp:CheckBox ID="chkDoSomething" runat="server"/>
</div>
<script>
$('input[type="checkbox"]').change(function () {
$(this).closest('div').css('pointer-events', 'none');
});
</script>
This is the same client-side solution as VDWWD's answer but written using native JS instead of jQuery, as you requested:
<script>
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("change", function() {
let div = this.closest("div");
div.style.pointerEvents = "none";
});
}
</script>
As noted, this requires each affected checkbox to be wrapped inside a <div>.

Calling first button on confirm of second button in javascript isn't working

I have two buttons in my html page and when someone clicks Generate button I want to save my document (the same thing save button is doing) if ok is clicked otherwise I do not want to do anything.
Js code
$("#save-application").trigger("click");
I also tried to use
document.getElementById('save-application').click();
and
$('#save-application').click();
But it isnt working.So basically I want to call my save button.Any suggestions on this?
I did tried
if (check == true) {
$("#form").submit();
return true;
}
else {
return false;
}
but form doesn't get saved
I think you missed # while querying by id $("#save-application").click();.
Instead of using trigger , you can create separate function for save functionality,
html code :
<input type="submit" value="Save" id="save-application" onclick="saveApplication();"/>
js code :
function saveApplication(){
//logic here
}
and then call saveApplication() instead of $("save-application").trigger("click");
So I'd do something like this on your input
<input id="save-application" type="submit" value="Save" onclick="saveApplication()"/>
Then modify your javascript to something like this:
function saveApplication() {
if (isChanged == true ) {
var check = confirm("Would you like to to save your changes and have a document generated?");
if (check == true) {
$("#save-application").trigger("click");
return true;
}
else { return false; }
} else {
return undefined;
}
}
Hope this helps

On Click When Button is Disabling then Click Button is not firing

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.

Check validation and disable button on click

I have an ASP.NET application and I have implemented the below code to disable users from double clicking and a submit button and thus the method behind the code is not executed than once.
OnClientClick="this.disabled = true; this.value = 'Submitting...';" UseSubmitBehavior="false" onclick="BtnSubmit_Click"
This was working perfectly, but on one of the pages I had implemented javascript forms validations and the below code is not working:
OnClientClick="return validation(); this.disabled = true;" UseSubmitBehavior="false" onclick="BtnAdd_Click"
The validation is to make sure user does not leave any empty fields, however on clicking the button if validation is success, the button is disabled but the onclick method is not being called.
Why exactly is this happening?
Rikket, you'll have to write separate code to prevent double submission of forms, once its submitted, a Jquery function will help probably, something like below, put this after your JavaScript validation function:
jQuery.fn.preventDoubleSubmission = function () {
var $form = $(this);
$form.on('submit', function (e) {
if ($form.data('submitted') === true) {
e.preventDefault();
} else {
$form.data('submitted', true);
}
}).find('input').on('change', function () {
$form.data('submitted', false);
});
return this;
};
And can be called after your validation inside the else :
if (nullFieldTracked == 'true') {
alert(nullExceptionMsg);
return false;
}
else {
$('form').preventDoubleSubmission();
}

Problem with enabling and disabling button control based on the asp.net check box check

Hi friends i have a button control which has to be enabled based on my asp.net checkbox check,but when run the code i am facing the problem my button is still disabled even after i perform a checkbox check .is their any property i have set in code behind to acccess the check event.
I am using the following code in my application
This is my javascript file
<script type="text/javascript">
function theChecker() {
var checkboxId = '<%= SpEligible.ClientID %>';
alert(checkboxId);
if (checkboxId.checked == true)
{
document.getElementById("SplistButton").disabled = false;
}
else
{
document.getElementById("SplistButton").disabled = true;
}
}
</script>
This is my code for the checkbox and button is
<asp:CheckBox ID="SpEligible" runat="server" Text="SpEligible" class="cBox" />
<asp:Button ID="SplistButton" runat="server" OnClientClick=" return ShowInsertForm()" Enabled="false"/>
This is my aspx.cs file where i am calling the javascript
SpEligible.Attributes.Add("onclick", "theChecker()");
I can see two major errors in your code :
1- In your <script> tag, you did realize that your Checkbox wouldn't have the same ID once in the page, but you didn't made that check. Also, as Ken Pespisa mentioned, the ID you took is only a string, therefore, it doesn't know any checked property. Here is the code I would write :
<script type="text/javascript">
function theChecker() {
var checkboxId = '<%= SpEligible.ClientID %>';
alert(checkboxId);
if (document.getElementById(checkboxId).checked == true)
{
document.getElementById("<%= SplistButton.ClientID %>").disabled = false;
}
else
{
document.getElementById("<%= SplistButton.ClientID %>").disabled = true;
}
}
</script>
2- In your .cs page, you don't seem to use any namespace. You may have hide some code, so I'll just say be sure to have namspaces and be sure to use this line inside a function, maybe the page load event function.
You need to change the javascript code to:
<script type="text/javascript">
function theChecker() {
var checkboxId = document.getElementById('<%= SpEligible.ClientID %>');
alert(checkboxId);
if (checkboxId.checked == true)
{
document.getElementById("SplistButton").disabled = false;
}
else
{
document.getElementById("SplistButton").disabled = true;
}
}
</script>
You were checking the checked property of a string constant. You need to get the control itself using document.getElementById which has checked property. I'd also rename "checkboxId" to "checkbox"
Change
document.getElementById("SplistButton")
to
document.getElementById(checkboxId)

Categories