Check validation and disable button on click - javascript

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();
}

Related

MVC - Issue with users double-clicking Submit button

I have a number of pages in my MVC app where the user clicks a Submit button to post a form. Sometimes users will click Submit and since nothing happens immediately, click it again. Therefore, the form submits twice. To prevent this, I have the following JavaScript code:
// When the user submits the form, disable the Save button so there is no chance
// the form can get double posted.
$('#form').submit(function () {
$(this).find('input[type=submit]').prop('disabled', true);
return true;
});
This code disables the Submit button so the user cannot click twice. This works fine. However, if there are client side validation errors on the form, the Submit button gets disabled but the form is never posted, and now the user cannot post the form. Is there a change I can make to the JS code to detect if there were client side validation errors, and, if so, I either don't disable the Submit button, or reenable it?
If you are using jQuery Validate, you can check to see if the form is valid before disabling the button:
$('#form').submit(function () {
if ($(this).valid()) {
$(this).find('input[type=submit]').prop('disabled', true);
}
});
You can try something like this:
<button id="subButton" /> <!-- do not use type="submit" because some browsers will automatically send the form -->
Javascript:
$('#subButton').click(function (e) {
e.preventDefault(); //prevent browser's default behaviour to submit the form
$(this).prop('disabled', true);
doValidation();
});
var pTimeout;
function doValidation() {
ajaxLoader.show(); //lock the screen with ajaxLoader
var form = $('#registerForm');
var isPending = form.validate().pendingRequest !== 0; // find out if there are any pending remote requests ([Remote] attribute on model)
if (isPending) {
if (typeof pTimeout !== "undefined") {
clearTimeout(pTimeout);
}
pTimeout = setTimeout(doValidation, 200); //do the validation again until there are no pending validation requests
}
var isValid = form.valid(); //have to validate the form itself (because form.Valid() won't work on [Remote] attributes, thats why we need the code above
if (!isPending) {
ajaxLoader.hide();
if (isValid) {
$('#registerForm').submit(); //if there are no pending changes and the form is valid, you can send it
}
else {
$('#subButton').prop('disabled', false); //else we reenable the submit button
}
}};
Switch it around.
$("input[type='submit']").on("click", function (event) {
event.preventDefault();
$(this).prop("disabled", true);
// perform error checking
if (noErrors) {
$("#form").submit();
}
else {
$(this).prop("disabled", false);
}
});

form is not doing submit after calling function return false only one time

I am trying to control form submitting after validating user input
the user must select at least one radio otherwise the form wouldn't submit
the first part is working very fine, if the user haven't select any radio input I call
$('form').submit(function () { return false });
else if he selected something I will call
$('form').submit();
but it is not submitting
function validateSelection() {
var temp = false;
$('.lang-radio > input[type=radio]').each(function () {
if ($(this).is(':checked')) {
temp |= $(this).is(':checked')
};
});
if (temp != 1) {
$('form').submit(function () { return false });
$('.high-light').effect("shake");
}
else {
$('form').submit();
}
}
I am calling the function validateSelection from OnClientClick="validateSelection();"
I am using asp.net webforms
When you do
$('form').submit(function () { return false });
you are attaching an event handler to the submit event. Thus, if this line executes first, then every time you do $('form').submit();, the event handler will be triggered and return false and not submit.
If the .Net control is a submit button, you can simply replace the first line with return false (Edit: and change it to OnClientClick="return validateSelection();"), otherwise you can remove it completely.
1) Remove OnClientClick="validateSelection();" from your form
2) Give class="validateForm" to your form
3) put following js code in you are js
$(document).ready(function(){
$('.validateForm').on('submit',function(){
var ckradio = $(this).find('[type=radio]:checked');
if(ckradio.length == 0){
return false;
}else{
return true;
}
});
});

How to capture an html form submit with javascript?

Currently I have several text inputs and then a type image submit button. On the submit button I have onmouseover, onmouseout, etc.. This sends those to a javascript function that handles change of images for a hover effect. What I wanna do is submit the form and then do some checking like do passwords match and such. Would I do something with the action attribute of the form tag to submit it to a javascript function?
Firstly I recommend using something like jQuery. It makes the code a lot easier to manage. Here's how you'd do it in jQuery:
$('form').submit(function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
Here's how you'd do it in pure javascript:
// function to make sure we add the event correctly no matter which browser
function addEvent(evnt, elem, func) {
if (elem.addEventListener) { // W3C DOM
elem.addEventListener(evnt,func,false);
} else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
} else { // No much to do
elem[evnt] = func;
}
}
// get first form on page
var form = document.forms[0];
addEvent('submit', form, function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
<form onsubmit="return cancel()"><input type="submit" /></form>
<script>
function cancel()
{
//code validation
var validated = false;
if(!validated)return false;
else return true;
}
</script>

Disallowing POST BACK when one is already in progress

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>

ASP.NET Post-Back and window.onload

I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks
When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}
Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}

Categories