I have an ASP.Net WebForms application where I am using jQuery validation. There are several buttons to submit the form, each with different options on the back end.
I have a custom validateForm() function that I can assign to the OnClientClick event of all the buttons, but I'm hoping for a more elegant solution where I don't have to specifically give each button the OnClientClick property.
So basically, is it possible to capture the $(form).submit() event before an asp button is submitted? Without using the OnClientClick attribute?
Solved: My issue was actually not because I couldn't catch the submit, but because the buttons were <a> links instead of inputs. I didn't realize this and made the post while at home trying to fix it from memory.
Any of the below solutions should work in the scenario above with actual submit buttons
Just attach a listener to the submit event:
$('form').on('submit', function (event) {
// Do whatever you need to do here ...
// You could also do `event.preventDefault();`,
// if you wanted to stop the submit.
});
You can use onsubmit event that will execute a JavaScript when a form is submitted from any button.
<form id="form1" runat="server" onsubmit="return ValidationFunction();">
And your JS function should return true or false as
function ValidationFunction() {
// Your jQuery validation
if (isValide) {
return true;
}
else {
return false;
}
}
Another option using JQuery to attaches an event handler to form submission
$(document).ready(function () { // << to make sure DOM is loaded
$('#form1').on('submit', function (e) {
e.preventDefault(); // << the default action of the event will not be triggered
var isValide = false;
if (isValide) {
alert('ok');
this.submit();
}
else {
alert('Not Valid');
}
});
});
I am both setting a form's action and submitting the form via the onclick event of a div:
<div class="action_button" onclick="document.forms['test'].action='url/to/action';document.forms['test'].submit()">
<span class="action_button_label">Save</span>
</div>
This works fine, but I'm wanting to use some code that conditionally checks for the 'Save' in the action_label_button, and only lets the submit() fire once. I'm trying to prevent multiple saves (which is yielding duplicate data in my app) from occurring.
// disable save buttons onclick (prevent multiple clicks of save buttons)
$('.action_button_label').one('click', function() {
// if the button is a save button
if($(this).html().indexOf('Save') != -1) {
// submit the parent form
$(this).html('<span class="action_button_label" style="color:gray;">Saving...</span>');
$(this).parents('form').submit();
}
});
$('form').bind('submit', function() {
$(this).find('action_button').attr('onclick', '');
});
This code doesn't seem to work as I expected. I'm afraid I'm a bit out of my depth here, any pointers would be great.
Try replacing
$(this).find('action_button').attr('onclick', '');
with
$(this).find('.action_button').attr('onclick', '');
You should always handle multiple submits server side to ENSURE you don't get them. However you can hide the button-label to assist with this client side.
$('.action_button_label').one('click', function() {
// if the button is a save button
if($(this).html().indexOf('Save') != -1) {
// submit the parent form
$('.action_button_label').hide(); //ADD THIS
$(this).html('<span class="action_button_label" style="color:gray;">Saving...</span>');
$(this).parents('form').submit();
}
});
$('form').bind('submit', function() {
$(this).find('action_button').attr('onclick', '');
});
I have used jQuery plugin: Validation
To validate some input fields, but I need to bypass validation when the user click the cancel button(which preforms a posts back)
Any help would be greatly appreciated
Sp
$("myButton").click(function () {
$("#mainform").validate().cancelSubmit = true;
$("#mainform").submit();
return false;
});
Actually I tried this and the answer is even simpler.
$("myButton").click(function () {
$("#mainform").validate().cancelSubmit = true;
});
The other two lines prevented my cancel button's submit action from working, so I whittled it down to just this one line and now it works great, validating on submit but not on cancel.
This allows my cancel button to submit the form with its Spring Web Flow event id regardless of the valid state of the form.
I have no idea if this is even possible, but I thought I would ask since it would be awesome if it is possible.
So basically I have a link with an onclick and in the onclick there are two calls. one to a function and another to _doPostBack.
The first function that is called is a simple function:
function CheckTerms() {
if (!document.Form.agreetoterms.checked) {
alert("Please check the terms and conditions.");
return false;
}
return true;
}
So basically if the check box isnt checked the alert happens and the page doesn't submit. If it is checked it submits. Right now even if it isn't checked, it shows the alert and executes the doPostBack and submits the page. The doPostBack is put into the link dynamically and I don't have access to it, which has made it harder for me. So any ideas or ways to abort it so it doesn't submit?
Thanks!
I'm assuming the _doPostback function handles the posting of the form, and that you don't want the anchor to move the page to the location of its href when clicked. preventDefault does this by preventing the anchor's default action from being taken when clicked.
var a = document.getElementById("yourAnchorId");
a.onclick = function(e){
e.preventDefault();
if (CheckTerms())
_doPostBack();
}
why can't you do the following:
function CheckTerms() {
if (!document.Form.agreetoterms.checked) {
alert("Please check the terms and conditions.");
return false;
}
else{
<<< call you function here >>>
}
return true;
}
I keep getting duplicate entries in my database because of impatient users clicking the submit button multiple times.
I googled and googled and found a few scripts, but none of them seem to be sufficient.
How can I prevent these duplicate entries from occurring using javascript or preferably jQuery?
Thanx in advance!
How about disabling the button on submit? That's what I do. It works fine.
$('form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
Disclaimer:
This only works when javascript is enabled on the user's browser. If the data that's being submitted is critical (like a credit card purchase), then consider my solution as only the first line of defense. For many use cases though, disabling the submit button will provide enough prevention.
I would implement this javascript-only solution first. Then track how many duplicate records are still getting created. If it's zero (or low enough to not care), then you're done. If it's too high for you, then implement a back-end database check for an existing record.
This should do the trick:
$("form").submit(function() {
$(":submit", this).attr("disabled", "disabled");
});
No JQuery?
Alternatively, you can make a check from db to check if a record already exist and if so, don't insert new one.
One technique I've seen used is to assign a unique ID to every form that's opened, and only accept one submission per form based on the ID.
It also means you can check how many times people aren't bothering to submit at all, and you can check if the submission genuinely came from your form by checking if it's got an ID that your server created.
I know you asked for a javascript solution, but personally I'd do both if I needed the robustness.
Preventing the double posting is not so simple as disabling the submit button. There are other elements that may submit it:
button elements
img elements
javascripts
pressing 'enter' while on some text field
Using jQuery data container would be my choice. Here's an example:
$('#someForm').submit(function(){
$this = $(this);
/** prevent double posting */
if ($this.data().isSubmitted) {
return false;
}
/** do some processing */
/** mark the form as processed, so we will not process it again */
$this.data().isSubmitted = true;
return true;
});
Here is bit of jQuery that I use to avoid the double click problem. It will only allow one click of the submit button.
$(document).ready(function() {
$("#submit").on('click', function() {
});
});
I'm not sure what language/framework you're working with or if it's just straight HTML. But in a Rails app I wrote I pass a data attribute on the form button disable_with which keeps the button from being clickable more than once while the transaction is in process.
Here's what the ERB looks like.
<%= f.button "Log In", class: 'btn btn-large btn-block btn-primary', data: {disable_with: "<i class='icon-spinner'></i>Logging In..."} %>
This is what I came up with in https://github.com/liberapay/liberapay.com/pull/875:
$('form').on('submit', function (e) {
var $form = $(this);
// Check that the form hasn't already been submitted
if ($form.data('js-submit-disable')) {
e.preventDefault();
return false;
}
// Prevent submitting again
$form.data('js-submit-disable', true);
// Set a timer to disable inputs for visual feedback
var $inputs = $form.find(':not(:disabled)');
setTimeout(function () { $inputs.prop('disabled', true); }, 100);
// Unlock if the user comes back to the page
$(window).on('focus pageshow', function () {
$form.data('js-submit-disable', false);
$inputs.prop('disabled', false);
});
});
The problem with the method described here is that if you're using a javascript validation framework and the validation fails, you won't be able to correct and re-submit the form without refreshing the page.
To solve this, you need to plug into the success event of your validation framework and only then, set the submit control to disabled. With Parsley, you can plug into the form validated event with the following code:
$.listen('parsley:form:validated', function(e){
if (e.validationResult) {
/* Validation has passed, prevent double form submissions */
$('button[type=submit]').attr('disabled', 'disabled');
}
});
If you are using client-side validation and want to allow additional submit attempts if the data is invalid, you can disallow submits only when the form content is unchanged:
var submittedFormContent = null;
$('#myForm').submit(function (e) {
var newFormContent = $(this).serialize();
if (submittedFormContent === newFormContent)
e.preventDefault(true);
else
submittedFormContent = newFormContent;
});
Found at How to prevent form resubmission when page is refreshed (F5 / CTRL+R) and solves the problem:
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
That is what I did to solve the problem.
I disabled the button for a second with adding setTimeout twice:
- the 1st time is to let the JS form fields verification work;
- the 2nd time is to enable the button in case if you have any verification on your back end, that may return an error, and hence the user will want to try to submit the form again after editing his data.
$(document).ready(function(){
$('button[type=submit]').on("click", function(){
setTimeout(function () {
$('button[type=submit]').prop('disabled', true);
}, 0);
setTimeout(function () {
$('button[type=submit]').prop('disabled', false);
}, 1000);
});
});