I have a button that saves the content that a user edits. I do not want them to hit the save button multiple times because of the load it causes on the server. I want to disable the button after they click on it.
Here is what I have attempted(doesn't work, though):
var active = true;
$("#save").click(function() {
if (!active) return;
active = false;
........
........
........
active = true;
The problem is that the user can still click on the element multiple times.
How can I fix this problem?
Edit: Sorry, I forgot to mention that I want to enable the click after the onclick code has finished executing.
Try this
$("#save").one('click', function() {
//this function will be called only once even after clicking multiple times
});
There is a disabled attribute: http://jsfiddle.net/uM9Md/.
$("#save").click(function() {
$(this).attr('disabled', true)
........
........
........
$(this).attr('disabled', false)
});
You can unbind the click handler, but I would go with .one as per #ShankarSangoli's answer (+1).
$("#save").click(function() {
// do things
$(this).unbind("click");
});
http://api.jquery.com/unbind/
If the element is an input you can do this really easily:
<input name="BUTTON" type="submit" value="Submit" onSubmit="document.BUTTON.disabled = true;">
That's some handy HTML Javascript integration stuff there.
Assuming:
<input type="button" id="save" ... />
You can either do:
$('#save').click(function(){
var $save = $(this);
//
// save code
//
$save.get(0).disabled = true;
});
Which disabled the button natively, or you can use jQuery's one functionality:
$('#save').one('click',function(){
//
// save code
//
});
Which will only execute once and must be re-bound. (But if you're deciding to enable/disable based on parameters, using the disabled attribute is probably a better choice.)
Related
I have some simple jQuery to change the text of a button once it's clicked
<button type="submit" id="zipUploadButton" class="btn btn-primary">Upload</button>
$uploadButton.click(function(){
$(this).text('please wait').attr("disabled", "disabled");
});
The trouble is it seems doing this blocks default behavior (a form submission, which I still want to happen). Is there a way to make sure the default behavior is preserved or an alternate way to do what I'm trying above that would work?
Disable the button in form submit event instead of the click event. The following code assume $form contains the parent form of $uploadButton.
$form.submit(function(){
$uploadButton.attr('disabled', 'disabled');
});
You can use a timeout to remove the disabled attribute in order to submit:
For JQuery 1.6+:
$('#zipUploadButton').click(function(){
var button = $(this);
button.prop('disabled', true);
setTimeout(function() {
button.prop('disabled', false);
},1000);
$("#form1").submit();
});
Otherwise, as mentioned in the comments, a form cannot be submitted if the button is disabled: more info
For JQuery 1.5 and below:
To set the disabled attribute, you could use:
button.attr('disabled','disabled');
And to enable again, use .removeAttr()
button.removeAttr('disabled');
Credits
You have to delay disabling the button until after the event has completed. Something like this should help you.
$uploadButton.click(function(){
var $this = $(this);
$this.text('please wait');
setTimeout(function(){
$this.attr("disabled", "disabled");
}, 10);
});
<input type="submit" name="btnADD" id="btnADD" value="ADD"/>
when user click add button twice, from get submitted twice with same data into table.
So Please help me to restrict user to submit from twice.
Once the form is submitted, attach a handler with jQuery that hijacks and "disables" the submit handler:
var $myForm = $("#my_form");
$myForm.submit(function(){
$myForm.submit(function(){
return false;
});
});
Returning "false" from the submit handler will prevent the form from submitting. Disabling buttons can have weird effects on how the form is handled. This approach seems to basically lack side effects and works even on forms that have multiple submit buttons.
try out this code..
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();" />
You can disable the button after clicking or hide it.
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="disableButton(this)"/>
js :
function disableButton(button) {
button.disabled = true;
button.value = "submitting...."
button.form.submit();
}
If you are working with java server side scripting and also using struts 2 then you refer this link which talks about on using token.
http://www.xinotes.org/notes/note/369/
A token should be generated and kept in session for the initial page render, when the request is submitted along with the token for the first time , in struts action run a thread with thread name as the token id and run the logic whatever the client has requested for , when client submit again the same request, check whether the thread is still running(thread.getcurrentthread().interrupted) if still running then send a client redirect 503.
And if you are not using any framework and looking for simple workout.
You can take help of the
java.util.UUID.randomUUID();
Just put the random uuid in session and also in hidden form field and at other side(the jsp page where you are handling other work like storing data into database etc.) take out the uuid from session and hidden form field, If form field matches than proceed further, remove uuid from session and if not than it might be possible that the form has been resubmitted.
For your help i am writing some code snippet to give idea about how to achieve the thing.
<%
String formId=(java.util.UUID.randomUUID()).toString();
session.setAttribute(formId,formId);
%>
<input type='hidden' id='formId' name='formId' value='<%=formId%>'>
You could notify the user that he drinks too much coffee but the best is to disabled the button with javascript, for example like so:
$("#btnADD").on('click', function(btn) {
btn.disabled = true;
});
I made a solution based on rogueleaderr's answer:
jQuery('form').submit(function(){
jQuery(this).unbind('submit'); // unbind this submit handler first and ...
jQuery(this).submit(function(){ // added the new submit handler (that does nothing)
return false;
});
console.log('submitting form'); // only for testing purposes
});
My solution for a similar issue was to create a separate, hidden, submit button. It works like so:
You click the first, visible button.
The first button is disabled.
The onclick causes the second submit button to be pressed.
The form is submitted.
<input type="submit" value="Email" onclick="this.disabled=true; this.value='Emailing...'; document.getElementById('submit-button').click();">
<input type="submit" id='submit-button' value="Email" name="btnSubmitSendCertificate" style='display:none;'>
I went this route just for clarity for others working on the code. There are other solutions that may be subjectively better.
You can use JavaScript.
Attach form.submit.disabled = true; to the onsubmit event of the form.
A savvy user can circumvent it, but it should prevent 99% of users from submitting twice.
You can display successful message using a pop up with OK button when click OK redirect to somewhere else
Disable the Submit Button
$('#btnADD').attr('disabled','disabled');
or
$('#btnADD').attr('disabled','true');
When user click on submit button disable that button.
<form onSubmit="disable()"></form>
function disable()
{
document.getElementById('submitBtn').disabled = true;
//SUBMIT HERE
}
Create a class for the form, in my case I used: _submitlock
$(document).ready(function () {
$(document).on('submit', '._submitlock', function (event) {
// Check if the form has already been submitted
if (!$(this).hasClass('_submitted')) {
// Mark the form as submitted
$(this).addClass('_submitted');
// Update the attributes of the submit buttons
$(this).find('[type="submit"]').attr('disabled', 'disabled');
// Add classes required to visually change the state of the button
$(this).find('[type="submit"]').addClass("buttoninactive");
$(this).find('[type="submit"]').removeClass("buttonactive");
} else {
// Prevent the submit from occurring.
event.preventDefault();
}
});});
Put a class on all your buttons type="submit" like for example "button-disable-onsubmit" and use jQuery script like the following:
$(function(){
$(".button-disable-onsubmit").click(function(){
$(this).attr("disabled", "disabled");
$(this).closest("form").submit();
});
});
Remember to keep this code on a generic javascript file so you can use it in many pages. Like this, it becomes an elegant and easy-to-reuse solution.
Additionally you can even add another line to change the text value as well:
$(this).val("Sending, please wait.");
Add a class to the form when submitted, stopping a user double clicking/submitting
$('form[method=post]').each(function(){
$(this).submit(function(form_submission) {
if($(form_submission.target).attr('data-submitted')){
form_submission.preventDefault();
}else{
$(form_submission.target).attr('data-submitted', true);
}
});
});
You can add a class to your form and your submit button and use jquery:
$(function() {
// prevent the submit button to be pressed twice
$(".createForm").submit(function() {
$(this).find('.submit').attr('disabled', true);
$(this).find('.submit').text('Sending, please wait...');
});
})
None of these solutions worked for me as my form is a chat and repeated submits are also required. However I'm surprised this simple solution wasn't offered here which will work in all cases.
var sending = 0;
$('#myForm').submit(function(){
if (sending == 0){
sending++;
// SUBMIT FORM
}else{
return false;
}
setTimeout(function(){sending = 0;},1000); //RESET SENDING TO 0 AFTER ONE SECOND
}
This only allows one submit in any one second interval.
I have following jQuery code to prevent double clicking a button. It works fine. I am using Page_ClientValidate() to ensure that the double click is prevented only if the page is valid. [If there are validation errors the flag should not be set as there is no postback to server started]
Is there a better method to prevent the second click on the button before the page loads back?
Can we set the flag isOperationInProgress = yesIndicator only if the page is causing a postback to server? Is there a suitable event for it that will be called before the user can click on the button for the second time?
Note: I am looking for a solution that won't require any new API
Note: This question is not a duplicate. Here I am trying to avoid the use of Page_ClientValidate(). Also I am looking for an event where I can move the code so that I need not use Page_ClientValidate()
Note: No ajax involved in my scenario. The ASP.Net form will be submitted to server synchronously. The button click event in javascript is only for preventing double click. The form submission is synchronous using ASP.Net.
Present Code
$(document).ready(function () {
var noIndicator = 'No';
var yesIndicator = 'Yes';
var isOperationInProgress = 'No';
$('.applicationButton').click(function (e) {
// Prevent button from double click
var isPageValid = Page_ClientValidate();
if (isPageValid) {
if (isOperationInProgress == noIndicator) {
isOperationInProgress = yesIndicator;
} else {
e.preventDefault();
}
}
});
});
References:
Validator causes improper behavior for double click check
Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)
Note by #Peter Ivan in the above references:
calling Page_ClientValidate() repeatedly may cause the page to be too obtrusive (multiple alerts etc.).
I found this solution that is simple and worked for me:
<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>
This solution was found in:
Original solution
JS provides an easy solution by using the event properties:
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){//activate on first click only to avoid hiding again on multiple clicks
// code here. // It will execute only once on multiple clicks
}
});
disable the button on click, enable it after the operation completes
$(document).ready(function () {
$("#btn").on("click", function() {
$(this).attr("disabled", "disabled");
doWork(); //this method contains your logic
});
});
function doWork() {
alert("doing work");
//actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
//I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
setTimeout('$("#btn").removeAttr("disabled")', 1500);
}
working example
I modified the solution by #Kalyani and so far it's been working beautifully!
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){ return true; }
else { return false; }
});
Disable pointer events in the first line of your callback, and then resume them on the last line.
element.on('click', function() {
element.css('pointer-events', 'none');
//do all of your stuff
element.css('pointer-events', 'auto');
};
After hours of searching i fixed it in this way:
old_timestamp = null;
$('#productivity_table').on('click', function(event) {
// code executed at first load
// not working if you press too many clicks, it waits 1 second
if(old_timestamp == null || old_timestamp + 1000 < event.timeStamp)
{
// write the code / slide / fade / whatever
old_timestamp = event.timeStamp;
}
});
you can use jQuery's [one][1] :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using count,
clickcount++;
if (clickcount == 1) {}
After coming back again clickcount set to zero.
May be this will help and give the desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
<p>Hello</p>
We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.
$(document).ready(function () {
$("#disable").on('click', function () {
$(this).off('click');
// enter code here
});
})
This should work for you:
$(document).ready(function () {
$('.applicationButton').click(function (e) {
var btn = $(this),
isPageValid = Page_ClientValidate(); // cache state of page validation
if (!isPageValid) {
// page isn't valid, block form submission
e.preventDefault();
}
// disable the button only if the page is valid.
// when the postback returns, the button will be re-enabled by default
btn.prop('disabled', isPageValid);
return isPageValid;
});
});
Please note that you should also take steps server-side to prevent double-posts as not every visitor to your site will be polite enough to visit it with a browser (let alone a JavaScript-enabled browser).
The absolute best way I've found is to immediately disable the button when clicked:
$('#myButton').click(function() {
$('#myButton').prop('disabled', true);
});
And re-enable it when needed, for example:
validation failed
error while processing the form data by the server, then after an error response using jQuery
Another way to avoid a quick double-click is to use the native JavaScript function ondblclick, but in this case it doesn't work if the submit form works through jQuery.
One way you do this is set a counter and if number exceeds the certain number return false.
easy as this.
var mybutton_counter=0;
$("#mybutton").on('click', function(e){
if (mybutton_counter>0){return false;} //you can set the number to any
//your call
mybutton_counter++; //incremental
});
make sure, if statement is on top of your call.
If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.
First set add a style to your button:
<h:commandButton id="SaveBtn" value="Save"
styleClass="hideOnClick"
actionListener="#{someBean.saveAction()}"/>
Then make it hide when clicked.
$(document).ready(function() {
$(".hideOnClick").click(function(e) {
$(e.toElement).hide();
});
});
Just copy paste this code in your script and edit #button1 with your button id and it will resolve your issue.
<script type="text/javascript">
$(document).ready(function(){
$("#button1").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script
Plain JavaScript:
Set an attribute to the element being interacted
Remove the attribute after a timeout
If the element has the attribute, do nothing
const throttleInput = document.querySelector('button');
throttleInput.onclick = function() {
if (!throttleInput.hasAttribute('data-prevent-double-click')) {
throttleInput.setAttribute('data-prevent-double-click', true);
throttleInput.setAttribute('disabled', true);
document.body.append("Foo!");
}
setTimeout(function() {
throttleInput.removeAttribute('disabled');
throttleInput.removeAttribute('data-prevent-double-click');
}, 3000);
}
<button>Click to add "Foo"!</button>
We also set the button to .disabled=true. I added the HTML Command input with type hidden to identify if the transaction has been added by the Computer Server to the Database.
Example HTML and PHP Commands:
<button onclick="myAddFunction(<?php echo $value['patient_id'];?>)" id="addButtonId">ADD</button>
<input type="hidden" id="hasPatientInListParam" value="<?php echo $hasPatientInListParamValue;?>">
Example Javascript Command:
function myAddFunction(patientId) {
document.getElementById("addButtonId").disabled=true;
var hasPatientInList = document.getElementById("hasPatientInListParam").value;
if (hasPatientInList) {
alert("Only one (1) patient in each List.");
return;
}
window.location.href = "webAddress/addTransaction/"+patientId; //reloads page
}
After reloading the page, the computer auto-sets the button to .disabled=false. At present, these actions prevent the multiple clicks problem in our case.
I hope these help you too.
Thank you.
One way I found that works is using bootstrap css to display a modal window with a spinner on it. This way nothing in the background can be clicked. Just need to make sure that you hide the modal window again after your long process completes.
so I found a simple solution, hope this helps.
all I had to do was create a counter = 0, and make the function that runs when clicked only runnable if the counter is = 0, when someone clicks the function the first line in the function sets counter = 1 and this will prevent the user from running the function multiple times when the function is done the last line of the code inside the function sets counter to 0 again
you could use a structure like this, it will execute just once:
document.getElementById('buttonID').addEventListener('click', () => {
...Do things...
},{once:true});
I've been trying to find the "right" way to prevent double submits of forms. There are lots of related posts on SO but none of them hit the spot for me. Two questions below.
Here is my form
<form method="POST">
<input type="text" name="q"/>
<button class="once-only">Send</button>
</form>
Here is my first attempt to disable double submits:
$(document).ready(function(){
$(".once-only").click(function(){
this.disabled = true;
return true;
});
});
This is the approach suggested here: Disable button after post using JS/Jquery. That post suggests the submitting element must be an input rather than a button, but testing both makes no difference. You can try it yourself using this fiddle: http://jsfiddle.net/uT3hP/
As you can see, this disables the button, but also prevents submission of the form. In cases where the submitting element is a button and an input element.
Question 1: why does this click handler stop submission of the form?
Searching around some more I find this solution (from Why doesn't my form post when I disable the submit button to prevent double clicking?)
if($.data(this, 'clicked')){
return false;
} else{
$.data(this, 'clicked', true);
return true;
}
You can play with this using this fiddle: http://jsfiddle.net/uT3hP/1/
This does work, but...
Question 2: Is this the best we can do?
I thought this would be an elementary thing. Approach 1 does not work, approach 2 does, but I don't like it and sense there must be a simpler way.
Simple and effective solution is
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
Source: here
You can use jQuery's submit(). In this case, it should look something like this:
$('form').submit(function(){
$(this).children('input[type=submit]').prop('disabled', true);
});
Here is a working jsFiddle (made by Mike) - http://jsfiddle.net/gKFLG/1/.
If your submit-button is not a direct child of the form-element you will need to replace children with find. Additionally, your submit-button may also be a button element instead of an input element. E.g. This is the case if you are using Bootstrap horizontal forms. Below is a different version of the snippet:
$('form').submit(function(){
$(this).find('button[type=submit]').prop('disabled', true);
});
Demo jsFiddle - http://jsfiddle.net/devillers/fr7gmbcy/
Similarly Ive seen a few examples, this one allows you to alter how long the button is disabled for, through timeout. It also only triggers on a form submit rather than on the buttons click event, which originally caused me a few issues.
$('form').submit(function () {
var button = $('#button');
var oldValue = button.value;
var isDisabled = true;
button.attr('disabled', isDisabled);
setTimeout(function () {
button.value = oldValue;
button.attr('disabled', !isDisabled);
}, 3000)
});
You could try using the following code:
$(document).ready(function(){
$(".once-only").click(function(){
this.submit();
this.disabled = true;
return true;
});
});
This should help:
<form class="form-once-only" method="POST">
<input type="text" name="q"/>
<button type="submit" class="once-only">Send</button>
</form>
Javascript:
$(document).ready(function(){
$("form.form-once-only").submit(function () {
$(this).find(':button').prop('disabled', true);
});
}
I have a form which is made like this:
<form id= 'lol' name = 'whyyyyy'>
<input name='dumbo'>
<input name='idiot'>
<input type='submit' value='I have no idea why its like this' onclick='document.lol.submit()'>
</form>
Now, I want to prevent the actual sending of the form, but so far all attempts failed.
My current code looks like this:
$(document).ready(function(){
$('form[name="whyyyyy"]').submit(function(e){
e.preventDefault();
alert(1);
return false;
});
})
but the inline submit command bypasses as it seems the jQuery function.
Can someone shred light into it?
EDIT:
The form CANNOT be changed, I don't have permission to change.
the on click code should trigger the submit function, it some complex validation wall of code in it. So I have to cache the submit action that it triggers, but I can't do that at moment.
the submit function should be triggered on send but it does not get triggered.
Here is an example of the code in jfiddle. As you can see it gets past by jQuery...
http://jsfiddle.net/StCPp/4/
if you don't need a submit button, why don't you use a regular button instead
<input type="button" />
<input type='button' value='i have no idea why he done it like this' onclick='document.getElementById('lol').submit()'>
Just use a normal button instead of a submit.
If you want to bypass a submit button you can make the class of the button cancel.
<input type='submit' class='cancel' value='i have no idea why he done it like this' onclick='document.lol.submit()'>
In your add-on JavaScript, remove the inline onclick event and replace it with whatever you desire. Problem solved.
You could also completely remove his button and replace it with one of your choice.
Remove the document.lol.submit function. This way, you can do whatever you want.
// Magic line
delete document.lol.submit;
// Or
$('form[name="whyyyyy"] input[type=submit]').attr('onclick', '');
$(document).ready(function(){
$('form[name="whyyyyy"]').submit(function(e){
e.preventDefault();
alert(1);
return false;
});
});
Ok so if I got this right you could remove the inline event handler onclick and add your custom handler (where you do the validation and all necessary steps):
$(document).ready(function() {
var $submit_button = $('input[type=submit]');
$submit_button.removeAttr('onclick');
$submit_button.click(function() {
//TODO: implement your custom handler
//execute validation etc.
});
});
Remove the onclick
$('input[type=submit]').attr('onclick','')
Then add the click event to function ready
$('input[type=submit]').on('click',function(){
//do your event
});
You aren't necessarily required to use jquery to implement this. You could use standard javascript.
$(document).ready(function(){
document.whyyyyy.submit = function(e){
alert(1);
return false;
};
});
This example works, but you might be hitting a jquery bug.