disable button with timeout - javascript

I have this form with conditions that alert validation errors before posting data. the problem is if someone double clicks (by mistake perhaps), the form is submitted, then the form is cleared on the first click then the second click will alert 'form empty', which could be confusing as it all happens in a split second. so what I want is to temporarily disable the button when clicked for 3 seconds. but what I have now just times out the whole function for 3 seconds not just disabling the button. how should I be doing this? here is a simplified version of the form. Thanks
$('#send').click(function(){
var self = $('#send');
setTimeout(function() {
self.disabled = false;
if(!$('#text').val()){
alert('field empty');
}else{
$('#message').html('done');
$('#text').val('');
}
}, 3000);
});

I've written a small example for you, of disabling a button on click. The timeout will enable the button after 3000 miliseconds.
Working demo
html:
<input id="text">
<input id="send" type="button" value="send"/>
<div id="message"></div>
Javascript:
$('#send').click(function(){
var button = $(this);
button.attr('disabled', 'disabled');
setTimeout(function() {
button.removeAttr('disabled');
},3000);
if(!$('#text').val()){
alert('field empty');
button.removeAttr('disabled');
}else{
$('#message').html('done');
$('#text').val('');
}
});

You could use jQuery's one() instead of click(). Once the function is run it will be unbound.
If you want to re-enable it you could put the timeout to re-bind it at the end of the function.
Using your method, it looks like you're never actually disabling the button:
this.disabled = 'disabled';

You are not correctly disabling the button. You are setting the .disabled property on a jQuery object, not the wrapped DOM element.
Try:
self.prop('disabled', false);
Instead of:
self.disabled = false;
EDIT:
Actually the code above was attempting to re-ebable the button. There was no code to disable the button.
I also think you want to perform the validation right away. The call to setTimeout() should just be for re-enabling the button, like this:
$('#send').click(function() {
var self = $(this);
// Disable the button.
self.prop('disabled', true);
// Process click.
if (!$('#text').val()) {
alert('field empty');
} else {
$('#message').html('done');
$('#text').val('');
}
// Cause the button to re-enable after 3 seconds.
setTimeout(function() {
self.prop('disabled', false);
}, 3000);
});

Related

Change submit button text and disable it in iOs

I have this piece of js code, it works on pc (change text to 'adding...' and disables a button). But on iOs devices only form is submitted, text is not changing. Any ideas?
$(".moveToBasket").click(function() {
var form = $(this).closest('form');
var button = $(this);
button.attr('value', 'Adding...');
form.on('submit', function() {
button.prop("disabled", true);
});
});
P.S. .moveToBasket class html element is 'input type="submit"'
I had the same problem a few days ago. It seems there are other people who confirmed the bug in Safari: https://github.com/rails/jquery-ujs/issues/306
I solved it like this:
$('body').on('submit', form, function formSubmitHandler(event){
// Shadow the form to prevent infinite loop
var form = event.target;
event.preventDefault();
// If <input type="submit">
button.attr('value', 'Adding...');
// If <button>Add</button>
button.text('Adding...');
button.prop('disabled', true);
// Submit the form in a different tick
setTimeout(function() {
form.submit();
}, 10);
});
I hope it helps.
Can you send me the HTML so I can see what needs to be done,
If it's a button element, you can do button.text('adding...')

How to disable submit button? [duplicate]

I wrote this code to disable submit buttons on my website after the click:
$('input[type=submit]').click(function(){
$(this).attr('disabled', 'disabled');
});
Unfortunately, it doesn't send the form. How can I fix this?
EDIT
I'd like to bind the submit, not the form :)
Do it onSubmit():
$('form#id').submit(function(){
$(this).find(':input[type=submit]').prop('disabled', true);
});
What is happening is you're disabling the button altogether before it actually triggers the submit event.
You should probably also think about naming your elements with IDs or CLASSes, so you don't select all inputs of submit type on the page.
Demonstration: http://jsfiddle.net/userdude/2hgnZ/
(Note, I use preventDefault() and return false so the form doesn't actual submit in the example; leave this off in your use.)
Specifically if someone is facing problem in Chrome:
What you need to do to fix this is to use the onSubmit tag in the <form> element to set the submit button disabled. This will allow Chrome to disable the button immediately after it is pressed and the form submission will still go ahead...
<form name ="myform" method="POST" action="dosomething.php" onSubmit="document.getElementById('submit').disabled=true;">
<input type="submit" name="submit" value="Submit" id="submit">
</form>
Disabled controls do not submit their values which does not help in knowing if the user clicked save or delete.
So I store the button value in a hidden which does get submitted. The name of the hidden is the same as the button name. I call all my buttons by the name of button.
E.g. <button type="submit" name="button" value="save">Save</button>
Based on this I found here. Just store the clicked button in a variable.
$(document).ready(function(){
var submitButton$;
$(document).on('click', ":submit", function (e)
{
// you may choose to remove disabled from all buttons first here.
submitButton$ = $(this);
});
$(document).on('submit', "form", function(e)
{
var form$ = $(this);
var hiddenButton$ = $('#button', form$);
if (IsNull(hiddenButton$))
{
// add the hidden to the form as needed
hiddenButton$ = $('<input>')
.attr({ type: 'hidden', id: 'button', name: 'button' })
.appendTo(form$);
}
hiddenButton$.attr('value', submitButton$.attr('value'));
submitButton$.attr("disabled", "disabled");
}
});
Here is my IsNull function. Use or substitue your own version for IsNull or undefined etc.
function IsNull(obj)
{
var is;
if (obj instanceof jQuery)
is = obj.length <= 0;
else
is = obj === null || typeof obj === 'undefined' || obj == "";
return is;
}
Simple and effective solution is
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
Source: here
This should take care of it in your app.
$(":submit").closest("form").submit(function(){
$(':submit').attr('disabled', 'disabled');
});
A more simplier way.
I've tried this and it worked fine for me:
$(':input[type=submit]').prop('disabled', true);
Want to submit value of button as well and prevent double form submit?
If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.
// Add class disableonsubmit to your form
$(document).ready(function () {
$('form.disableonsubmit').submit(function(e) {
if ($(this).data('submitted') === true) {
// Form is already submitted
console.log('Form is already submitted, waiting response.');
// Stop form from submitting again
e.preventDefault();
} else {
// Set the data-submitted attribute to true for record
$(this).data('submitted', true);
}
});
});
Your code actually works on FF, it doesn't work on Chrome.
This works on FF and Chrome.
$(document).ready(function() {
// Solution for disabling the submit temporarily for all the submit buttons.
// Avoids double form submit.
// Doing it directly on the submit click made the form not to submit in Chrome.
// This works in FF and Chrome.
$('form').on('submit', function(e){
//console.log('submit2', e, $(this).find('[clicked=true]'));
var submit = $(this).find('[clicked=true]')[0];
if (!submit.hasAttribute('disabled'))
{
submit.setAttribute('disabled', true);
setTimeout(function(){
submit.removeAttribute('disabled');
}, 1000);
}
submit.removeAttribute('clicked');
e.preventDefault();
});
$('[type=submit]').on('click touchstart', function(){
this.setAttribute('clicked', true);
});
});
</script>
How to disable submit button
just call a function on onclick event and... return true to submit and false to disable submit.
OR
call a function on window.onload like :
window.onload = init();
and in init() do something like this :
var theForm = document.getElementById(‘theForm’);
theForm.onsubmit = // what ever you want to do
The following worked for me:
var form_enabled = true;
$().ready(function(){
// allow the user to submit the form only once each time the page loads
$('#form_id').on('submit', function(){
if (form_enabled) {
form_enabled = false;
return true;
}
return false;
});
});
This cancels the submit event if the user tries to submit the form multiple times (by clicking a submit button, pressing Enter, etc.)
I have been using blockUI to avoid browser incompatibilies on disabled or hidden buttons.
http://malsup.com/jquery/block/#element
Then my buttons have a class autobutton:
$(".autobutton").click(
function(event) {
var nv = $(this).html();
var nv2 = '<span class="fa fa-circle-o-notch fa-spin" aria-hidden="true"></span> ' + nv;
$(this).html(nv2);
var form = $(this).parents('form:first');
$(this).block({ message: null });
form.submit();
});
Then a form is like that:
<form>
....
<button class="autobutton">Submit</button>
</form>
Button Code
<button id="submit" name="submit" type="submit" value="Submit">Submit</button>
Disable Button
if(When You Disable the button this Case){
$(':input[type="submit"]').prop('disabled', true);
}else{
$(':input[type="submit"]').prop('disabled', false);
}
Note: You Case may Be Multiple this time more condition may need
Easy Method:
Javascript & HTML:
$('form#id').submit(function(e){
$(this).children('input[type=submit]').attr('disabled', 'disabled');
// this is just for demonstration
e.preventDefault();
return false;
});
<!-- begin snippet: js hide: false console: true babel: false -->
<form id="id">
<input type="submit"/>
</form>
Note: works perfectly on chrome and edge.
The simplest pure javascript solution is to simply disable the button:
<form id="blah" action="foo.php" method="post" onSubmit="return checkForm();">
<button id="blahButton">Submit</button>
</form>
document.getElementById('blahButton').disabled = true ;
It works with/without onSubmit. Form stays visible, but nothing can be sumbitted.
In my case i had to put a little delay so that form submits correctly and then disable the button
$(document).on('submit','#for',function()
{
var $this = $(this);
setTimeout(function (){
$this.find(':input[type=submit]').attr('disabled', 'disabled')
},1);
});

Need click event to trigger alert during else

So, this code is working:
<script>
$(document).ready(function(){
  var btn = $('#submit_send_order');
  btn.attr({disabled: 'disabled'});
  var chk = $('.end-box');
  chk.click(function(){
    if ($(this).attr('checked'))
      btn.removeAttr('disabled');
    else
      btn.attr({disabled:'disabled'});
  });
});
</script>
but I can't get any working version of a click, onclick, or event handler to cause a popup message during the else condition. Unless users checks a box, they cannot send their order on my site. Right now they click the button and nothing happens until they check the box. But I'd like an alert to show as well, e.g.:
$(document).ready(function(){
$('#submit_send_order').click(function(){
alert("You cannot proceed until you check the end box");
});
});
As Verhaeren said above, if the button is disabled, then it can't fire the click event. Rather than disabling the button, I would just put an if/else check in the click event.
So...
$(document).on('click', '#submit_send_order', function(event) {
event.preventDefault();
if ($('.end-box').prop('checked')) {
//Handle form submission
} else {
alert('You cannot proceed until you check the end box');
}
});
The onclick event doesn't fire when the element is disabled. Also, notice which is the right method to see if the checkbox is checked:
$(document).ready(function(){
var btn = $('#submit_send_order');
btn.attr({disabled: 'disabled'});
var chk = $('.end-box');
chk.on('click', function(){
if ($(this).is(':checked'))
btn.removeAttr('disabled');
else
btn.attr({disabled:'disabled'});
});
btn.on('click', function(){
alert("You cannot proceed until you check the end box");
});
});
I build a "solution" for this if you REALLY whant to do that. You can check it at this fiddle:
http://jsfiddle.net/2f1wsb8c/3/
It's placing an element with the same size of the button over it to catch the click when the button is disabled.

Is there a way to check if a postback is in progress?

In the case that a button is clicked multiple times on a page - Is there a way to figure out using javascript/jquery that a postback is already in progress and cancels the new attempt to submit the page?
Thanks
You can avoid users from double clicking by disabling whatever form elements can cause a form submit.
Checkout http://greatwebguy.com/programming/dom/prevent-double-submit-with-jquery/ for an example.
You can disable the button on first click, so that you could not click it when the post is in progress, and re enable it when the post-back has finished.
<script type="text/javascript" language="JavaScript">
var submitted = false;
function SubmitTheForm() {
if(submitted == true) { return; }
document.myform.submit();
document.myform.mybutton.value = 'Thank You!';
document.myform.mybutton.disabled = true;
submitted = true;
}
</script>
<form method="post" action="#">
<input type="submit" onclick=return SubmitTheForm()>
</form>
you could always just disable the button in the onclick handler.
$('input[type="submit"]').click(function(e) {
e.preventDefault();
var self = this;
$(self).attr('disabled', 'disabled');
$.post('url',$(self).closest('form').serialize(), function() {
$(self).removeAttr('disabled'); // re-enable after request complete.
});
});
You could have your click event set a variable in your click handler to true and only allow the handler to proceed when the value is false. Of course you will have to set it to false again when your callback finishes.
if (!processInProgress) {
processInProgress = 1
// start the process
}

properly disabling the submit button

this is the code that I use to disable the button
$("#btnSubmit").attr('disabled', 'disabled')
$("#btnSubmit").disabled = true;
and this is my submit button
<input id="btnSubmit" class="grayButtonBlueText" type="submit" value="Submit" />
the button although looks disabled, you can still click on it.. This is tested with FF 3.0 and IE6
Am I doing something wrong here?
If it's a real form, ie not javascript event handled, this should work.
If you're handling the button with an onClick event, you'll find it probably still triggers. If you are doing that, you'll do better just to set a variable in your JS like buttonDisabled and check that var when you handle the onClick event.
Otherwise try
$(yourButton).attr("disabled", "true");
And if after all of that, you're still getting nowhere, you can manually "break" the button using jquery (this is getting serious now):
$(submitButton).click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
});
That should stop the button acting like a button.
Depending on how the form submission is handled you might also need to remove any click handlers and/or add one that aborts the submission.
$('#btnSubmit').unbind('click').click( function() { return false; } );
You'd have to add the click handler's again when (if) you re-enable the button.
You need to process Back/Prev button into browser.
Example bellow
1) Create form.js:
(function($) {
$.enhanceFormsBehaviour = function() {
$('form').enhanceBehaviour();
}
$.fn.enhanceBehaviour = function() {
return this.each(function() {
var submits = $(this).find(':submit');
submits.click(function() {
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = this.name;
hidden.value = this.value;
this.parentNode.insertBefore(hidden, this)
});
$(this).submit(function() {
submits.attr("disabled", "disabled");
});
$(window).unload(function() {
submits.removeAttr("disabled");
})
});
}
})(jQuery);
2) Add to your HTML:
<script type="text/javascript">
$(document).ready(function(){
$('#contact_frm ).enhanceBehaviour();
});
</script>
<form id="contact_frm" method="post" action="/contact">
<input type="submit" value="Send" name="doSend" />
</form>
Done :)

Categories

Resources