I have the following submit button on all my asp.net web application, to create or edit records:-
<input type="submit" value="Save" class="btn btn-primary"/>
But I need to write a jQuery to disable the button once the user click on it (to avoid successive API calls to an external system,). So I wrote this code, but the button will not be disabled once clicked on.
$(".btn btn-primary").click(function () {
$("input[type=submit]").attr("disabled", "disabled");
$("input[type=submit]").css("background-color", "grey");
});
Second question which approach I should follow, incase I need to re-enable the button again incase a model state error occur , after click on the submit button. can anyone advice please
Try this:
$(".btn.btn-primary").click(function () {
$("input[type=submit]").attr("disabled", "disabled");
$("input[type=submit]").css("background-color", "grey");
return false;
});
Your selector is wrong
$(".btn.btn-primary").click(function () {
$(this).prop("disabled", "disabled").css("background-color", "grey");
});
this
change this
$(".btn btn-primary").click(function () {
$("input[type=submit]").attr("disabled", "disabled");
$("input[type=submit]").css("background-color", "grey");
});
for
$(".btn .btn-primary").click(function (e) {
$(this).attr({disabled:true});
$("input[type=submit]").css("background-color", "grey");
});
$(".btn.btn-primary").click(function () {
$(this).attr('disabled','disabled');
}
try
$(".btn.btn-primary").click(function () {
$(this).attr("disabled", "disabled")
.css("background-color", "grey");
e.preventDefault();
});
To re-enable at a later stage use
$("input[type=submit]").removeAttr("disabled");
None of the solutions above take into account whether or not the form submission was successful. What if the user forgot to complete a required a field? She would receive an error message, attempt to correct the error and then discover that she can not resubmit the form. Even if you solve that issue, once the user refreshes the page she can submit again.
What is the purpose of the form? If for example it is a registration form, I would simply fire an Ajax method once the email address has been entered which checks for the email address in the database and prevents the user from attempting to register the same email address twice. If on the other hand you are doing a survey and you wish to discourage multiple submissions from the same user I would create a cookie. On DOM ready your script would look for the cookie. If the cookie is present do not display the form.
Related
Please pardon me if it is a basic thing, because I am a new learner of Javascript/jQuery. I have been trying to disable submit button to disable multiple submits. I have come across multiple solutions here as well, but all those used specific form name. But I wanted to apply a global solution for all forms on all pages so I dont have to write code on each page, so I put this in footer, so all pages have:
$('input:submit').click(function(){
$('input:submit').attr("disabled", true);
});
This code works on all the forms in all pages as I wanted, but if there are HTML5 required fields in form and form is submitted without them, of course notifications are popped but button still gets disabled. So, I tried with this:
$('input:submit').click(function(){
if ($(this).valid()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
But this does not work. Kindly help me so that jQuery only disables when all HTML5 validation is done. Thanks
Try this and let me know:
$('input:submit').click(function(){
if ($(this).closest("form").checkValidity()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
Ruprit, thank you for the tip. Your example did not work for me (in Firefox), but it helped me a lot.
Here is my working solution:
$(document).on("click", ".disable-after-click", function() {
var $this = $(this);
if ($this.closest("form")[0].checkValidity()) {
$this.attr("disabled", true);
$this.text("Saving...");
}
});
Since checkValidity() is not a jQuery function but a JavaScript function, you need to access the JavaScript element, not the jQuery object. That's the reason why there has to be [0] behind $this.closest("form").
With this code you only need to add a class="disable-after-click" to the button, input, link or whatever you need...
It is better to attach a handler to the submit event rather than a click event, because the submit event is only fired after validation is successful. (This saves you from having to check validity yourself.)
But note that if a submit button is disabled then any value they may hold is NOT submitted to the server. So we need to disable the inputs after form submission.
The question is compounded by the new HTML5 attribute form which allows associated inputs to be anywhere on the page as long as their form attribute matches a form ID.
This is the JQuery snippet that I use:
$(document).ready( function() {
$("form").on("submit", function(event) {
var $target = $(event.target);
var formId = $target.attr("id");
// let the submit values get submitted before we disable them
window.setTimeout(function() {
// disable all submits inside the form
$target.find("[type=submit]").prop("disabled", true);
// disable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", true);
}, 2); // 2ms
});
});
---[ WARNING ]---
While disabling submit buttons prevents multiple form submissions, the buttons have the unfortunate side effect of staying disabled should the user click the [Back] button.
Think about this scenario, the user edits some text, clicks submit (and get redirected to different page to view the edits), clicks back to edit some more, ... and ... they can't re-submit!
The solution is to (re-)enable the submit button on page load:
// re-enable the submit buttons should the user click back after a "Save & View"
$(document).ready( function() {
$("form").each(function() {
var $target = $(this);
var formId = $target.attr("id");
// enable all submits inside the form
$target.find("[type=submit]").prop("disabled", false);
// enable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", false);
});
});
Try this
`jQuery('input[type=submit]').click(function(){ return true;jQuery(this).prop('disabled','disabled');})`
run this code on successful validation of the form
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'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.
$('form').submit(function() {
...code done here to validate form fields
});
The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?
I asked this same question: How can I get the button that caused the submit from the form submit event?
The only cross-browser solution I could come up with was this:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val()
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
Not sure if its the answer you're looking for but you should change the "Cancel" button to an anchor tag. There's no need to submit a cancel unless you're doing work on the form values.
well this will only fire if the type of the input button is like so:
<input type='submit' ...
so make sure the cancel button does not have type='submit' and it should work
EDIT
This only works in FF and not in Chrome (and I so, I imagine, not in other WebKit based browsers either) so I'm just leaving this here as a browser specific workaround, an interesting note but not as the answer.
#Neal's suggestion of NOT making the cancel button of type submit is probably the cleanest way. However, if you MUST do it the way you are doing it now:
$('form').submit(function(e){
if(e.originalEvent.explicitOriginalTarget.id === 'cancel'){
//don't validate
}
else{
//validate
}
});
var myForm = $('form');
$('input[type="submit"]',myForm).click(function(e) {
var whoClickedsubmit = $(e.target); //further, you can use .attr('id')
//do other things here
});
EDIT
.submit(function(event){
var target = event.originalEvent.explicitOriginalTarget.value;
//But IE does not have the "explicitOriginalTarget" property
});
I am disabling my submit buttons when submitting a form, for preventing the user to submit the form multiple times.
$(function ()
{
$("form").submit(function ()
{
$(":submit", this).attr("disabled", "disabled");
});
});
But if the client validation fails I want to enable the button again.
I am using asp.net mvc unobtrusive client validation
You can use the jQuery One event as detailed in this answer.
Most solutions to this issue revolve around testing $("form").valid() - you could probably use this in your function to determine whether to disable the submit button.
You have to check if there is any error before disabling the submit button
$('#myform').submit(function () {
if ($(this).find('.input-validation-error').length == 0) {
$(this).find(':submit').attr('disabled', 'disabled');
}
});
Hope it helps!
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);
});
});