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);
}
});
Related
I have a form which is submitted using Ajax.
If a checkbox is checked (receive latest offers and such), I would like to prevent the form from being submitted, if the fields are not filled out.
If the checkbox is not checked, then I don't care if the fields are filled out, and the form can be submitted even if empty.
The problem I'm currently having is, that the form is being submitted even if the checkbox is checked and the fields are empty.
I tried return false, event.stopImmediatePropagation(), event.stopPropagation() and event.preventDefault();. None of them prevent the form from submitting.
function check() is attached to the submit button.
Any and all advice is welcome.
If I can provide any additional information, let me know.
Thank you
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
return false; //event.preventDefault()//etc etc
}
if (!email.validity.valid) {
showEmailError();
return false; //event.preventDefault()//etc etc
}
};
};
setTimeout(function() {
document.getElementById("allow").addEventListener("click", sendAjax);
}, 1);
<button id="allow" onclick="check()">
<span id="a"></span>
</button>
As chandan suggested, I edited function check() and it works.
RollingHogs answer should also work, but the button I'm using is not type submit, as a few other ajax functions need to run before the form is submitted, so I can not accept that.
Anyway, this is the code that does the job:
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if(!fname.validity.valid && !email.validity.valid){
showNameError();
showEmailError();
}else if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
}else if(!email.validity.valid) {
showEmailError();
}else{
sendAjax();
}
}else{
sendAjax();
};
};
I guess the problem is that you stop button.onclick from propagation, not form.onsubmit. Try moving check() from onclick to onsubmit:
<form id="fname" ... onsubmit="check(event)">
<button id="allow" type="submit"></button>
</form>
Function check() should work without any edits then.
Also, see code from this question
I have a form where and AJAX function runs on form submission to make sure that the data in the form doesn't conflict with data in the database. If a conflict is found, the AJAX function pops up a confirm() box. If the user clicks "OK", the form is submitted. If they click "Cancel", the form is not submitted.
Here's where things get problematic. If they click cancel and then adjust the values in the form and submit it again, the AJAX function does not run the next time they hit the form submit button. Is there a way to make the AJAX function run every time they hit submit, even if they have previously cancelled the form submission?
Here is a truncated version of the AJAX function:
$('#publish').one('click', function (e) {
e.preventDefault();
var url = shiftajax.ajaxurl;
var shift = $('#post_ID').val();
var data = {
'action': 'wpaesm_check_for_schedule_conflicts_before_publish',
'shift': shift,
};
$.post(url, data, function (response) {
if( response.action == 'go' ) {
// submit the form
$('#post').submit();
} else {
// ask user for confirmation
if (confirm(response.message)) {
// user clicked OK - submit the form
$('#post').submit();
} else {
// user clicked cancel - do nothing
}
}
});
});
Like I said, this is working just fine, but the AJAX doesn't fire at all if you hit the submit button after hitting the "cancel" button.
For what it is worth, this AJAX function runs when you hit the "Publish" button on a WordPress custom post type.
Dont use one(it will fire ajax submit or button click only once) , use here var IsBusy to check user is not repeatedly pressing the form submit,
Try below code,
var isBusy = false; //first time, busy state is false
$('#publish').on('click', function (e) {
if(isBusy == true)
return ; //if Busy just return dont submit
else
isBusy= true; //true , tell that ajax is now busy processing a request
e.preventDefault();
var url = shiftajax.ajaxurl;
var shift = $('#post_ID').val();
var data = {
'action': 'wpaesm_check_for_schedule_conflicts_before_publish',
'shift': shift,
};
$.post(url, data, function (response) {
if( response.action == 'go' ) {
// submit the form
$('#post').submit();
} else {
// ask user for confirmation
if (confirm(response.message)) {
// user clicked OK - submit the form
$('#post').submit();
} else {
// user clicked cancel - do nothing
}
}
isBusy = false;
});
});
Is there any method to check if the mail (in a registration form) exist in my database while i'm writing it (before i click submit buttom).
This is my javascript function it work well when I click submit button:
<script type="text/javascript">
$(document).ready(function(){ //newly added
$('#_submit').click(function() {alert('in');
var emailVal = $('#mail').val(); // assuming this is a input text field
$.post('checkemail.php', {'mail' : emailVal}, function(data) {
if(data=='exist') return false;
else $('#form1').submit();
});
});
});
</script>
but I want to verify the mail before I submit (without I click any button)
I believe #_submit is a submit button. In that case, your <from> will be submitted without waiting for the ajax call to complete, since that is an asynchronous task.
In order to work around this, you should prevent the <form> submission by default, and once the ajax call completes, decide whether to submit the form or not depending on the response.
$(document).ready(function() { //newly added
$('#_submit').click(function(e) {
e.preventDefault(); // prevent default submission
alert('in, submission prevented - waiting for ajax response');
var emailVal = $('#mail').val(); // assuming this is a input text field
$.post('checkemail.php', {
'mail': emailVal
}, function(data) {
if (data == 'exist')
return false;
else
$('#form1').submit();
});
});
});
or you can simply use a type="button" button so that it doesn't trigger <form> submission.
something like that
$.ajax(url).done(function(response) {
if (response === true) {
$(form).submit();
} else {
console.log("not allowed");
});
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();
}
I have initialized my form submission like following:
$(document).ready(function() {
$("#my_form").submit(function(e) {
...
...
}
}
As you see above, it is in $(document).ready(...). When user press "Submit" button on UI, the form will be submitted.
But, How can I also trigger this form submission in Javascript besides user input (e.g. press submit button on UI)?
Call the submit() DOCs method on the form.
$("#my_form").submit();
You can use $("#my_form").submit();
$(document).ready(function () {
$("#SubmitForm").click(function (e) {
var textContent = $("#TextContent").val();
textContent = jQuery.trim(textContent);
if (textContent == "") {
alert("Content field cannot be empty.");
$("#TextContent").focus();
return false;
}
else{ $("#my_form").submit();
}
});
});