I am nearly finished my website, but my last problem is, I want to include a Loading.gif on the Follow-Button after hitting the submit-button 'Follow'. For this I need to submit the form-data after a delay. For showing the loading.gif on hitting submit, I dont need help, just for the delay.
I tried different codes but they didnt work. Here are all the codes:
My Form-Tag with submit-button:
<form id=followForm action="" method="POST"><input type="submit" name="follow" class="btn_id9 shadow rounded-min ptr" value="Follow User" style="width:100%" /></form>
And here the code-sample, which didnt work:
function formdelay(followform) {
$(function() {
setTimeout(function() { $('#followForm').submit(); }, 2000);
});
}
I hope you guys can help me, thanks!
This is an interesting problem. The first thought that I had was to do something like this:
http://jsfiddle.net/V9UpA/
$('#followForm').on('submit', function (event, force) {
if (!force) {
var $this = $(this);
event.preventDefault();
setTimeout(function () {
$this.trigger('submit', true);
}, 2000);
}
});
Basically, you want to use event.preventDefault() on the initial submit event, followed by a timeout. After that timeout has completed, you re-trigger the event, but pass the force argument so that we want to allow the submit this time around.
What you need to do is something like this:
$("#followForm input").click(function(e) {
e.preventDefault();
setTimeout(function() { $("#followForm").submit(); }, 2000);
});
The key is e.preventDefault(). This method will stop the default behavior of clicking on the submit button (which is submitting on the form). You can then do whatever you need to do and then submit the form manually which is what $("#followForm").submit(); does.
Demo: http://jsfiddle.net/DMcCr/2/
Related
I want a really simple thing to happen on my page, after the user submits the form, there must be a delay before the form is actually submitted, however it doesn't seem to work html form:
<form action='index.php' method='get'>
<input type='submit' value='Reset' name='resetBtn' onClick='PreSubmit(this.form)'>
</form>
javascript function:
function PreSubmit(form) {
var func = function () {
form.submit();
}
setTimeout(func, 10000);
}
so I am really really new to javascript, but how I see it, onlick event must call this javascript function, it should wait 10 seconds and only then submit the form and update the page, however the form is submitted right away, why? and how do I make it wait before submitting? any kind of help would be appreciated
You need to stop the default behavior of the submit button. Lot's of folks make the mistake of returning false to do this, but that's not quite right and it's important to understand what returning false is doing. This isn't the best way (unobtrusive JS is a whole different subject), but to accomplish what you want with minimal changes do something like the following
HTML:
<form action='index.php' method='get'>
<input type='submit' value='Reset' name='resetBtn' onClick='PreSubmit(event, this.form)'>
</form>
JS:
function PreSubmit(event, form) {
if (event.preventDefault) {
event.preventDefault();
}
else {
event.returnValue = false;
}
var func = function () {
form.submit();
}
setTimeout(func, 10000);
}
add return to onclick.
onClick='return PreSubmit(this.form)'>
And add return false to PreSubmit.
function PreSubmit(form){
....
//this will stop the click event
return false;
}
So PreSubmit return false -> onClick return false, which will stop the submit button action.
http://jsfiddle.net/KVsQ4/
I think there's another problem you would consider, what'll happen if the user continuously click the button. wait another 10 secs(which means you should clearTimeout the previous timeID), or just disable it when the user click it the first time.
You need to make it a type="button", not a type="submit"
At the end of the document I have:
<script>
$("#submitEvent").click(function() {
$("#eventForm").submit();
});
$(document).ready(function() {
$('#eventForm').submit(function() {
console.log("I am on submit");
}); });
</script>
Now submitEvent is button which is not within a form so and the reason for having on .click event.
When button is pressed the form submit is triggered correctly:
<form id="eventForm" action="${contextPath}/dashboard/event/new"
method="post">
Now I expect another event to be fired when submit is fired which actually is ignored for some reason. Instead of console.log I am not surprisingly going to use ajax, but even console.log does not print anything so the event is not triggered..
Update, did as you suggested still nothing :-) :
$(document).ready(function() {
$("#submitEvent").click(function() {
$("#eventForm").submit();
});
$('#eventForm').submit(function() {
console.log("I am on submit");
});
});
If your reason for saying the form submit handler isn't being called is that you don't see the output in the console, remember that submitting a form completely tears down and replaces the page. You probably don't have time to see the log message before the console gets cleared.
In a comment, you said:
Hm, so how can I check if ajax will be called.
You can check by setting a breakpoint on your console.log statement and seeing if the breakpoint gets hit. Or if you want to debug 1990's-style, use an alert.
But note that doing ajax from within a form submit handler, if the form's result will replace the page, is unreliable. (If the form's result won't replace the page, you're probably fine.) This is because ajax is asynchronous, meaning your submit handler could start it, but it wouldn't have time to finish before being cancelled by the teardown.
Try this...
$(document).ready(function() {
$("#submitEvent").click(function() {
$("#eventForm").submit();
});
$('#eventForm').submit(function(e) {
e.preventDefault();
console.log("I am on submit");
});
});
It will stop the form submitting so you can see, for now, if the event is actually being triggered or not.
It may simply be that the form being submitted is reloading the page before you see the console output.
You just need to move your code inside the ready function
<script>
$(document).ready(function() {
$("#submitEvent").click(function() {
// run ajjax code here
});
$('#eventForm').submit(function(e) {
e.preventDefault(); // stops the page from submiting
console.log("I am on submit");
});
});
</script>
I updated the code, you don't need to submit the form. just run ajax on click.
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 know there are a lot of questions about it, but I tried several solutions, and nothing works.
In my django app I have a form:
<form method='post'>
<button type='submit'>Send</button>
</form>
I wan't to disable the button once the user has submitted the form. Using other questions, I tried several things, like:
<button type='submit' onclick="this.disabled=true">Send</button>
When I click, the button is disabled... but the form is not submitted. And for each try I had the same issue: either the button is disabled or the form is submitted. I can't find how to do both...
I'm using Chrome. Any idea on why I have this problem? Thank you for your help.
Try this:
$('form').submit(function() {
$(this).find("button[type='submit']").prop('disabled',true);
});
I like this, don't have to traverse the DOM.
Put function on a setTimeout function, this allows make submit and after disable button, even if setTimeout is 0
$(document).ready(function () {
$("#btnSubmit").click(function () {
setTimeout(function () { disableButton(); }, 0);
});
function disableButton() {
$("#btnSubmit").prop('disabled', true);
}
});
You could disable it upon the parent form's submit event:
$("form").on("submit", function () {
$(this).find(":submit").prop("disabled", true);
});
Be sure to run this code only after the HTMLFormElement has been loaded, or else nothing will be bound to it. To ensure that the binding takes place, fire this off from within a document-ready block:
// When the document is ready, call setup
$(document).ready(setup);
function setup () {
$("form").on("submit", function () {
$(this).find(":submit").prop("disabled", true);
});
}
Something like this might work.
<button id="btnSubmit" type='submit'> Send </button>
<script>
$("#btnSubmit").on("click", function(e){
e.PreventDefault();
$(this).closest("form")[0].submit();
$(this).prop('disabled',true)
});
</script>
Try, like this,
<input type="submit" value="Send" onclick="javascript=this.disabled = true; form.submit();">
This ended up being the best solution for me
$("form").submit(function disableSubmit() {
$("input[type=submit]", this).prop("disabled", true);
});
my variant, disable button, no direct disabled but only vidible hidden:
<input type="submit" name="namebutton" value="Nahrát obrázek" onclick="this.style.visibility='hidden';" ondblclick="this.style.visibility='hidden';"/>
You can do something like this. It is work fine with me.
<form method='post' onSubmit='disableFunction()'>
// your code here
</form>
Then in script, add this
<script>
function disableFunction() {
$('#btn_submit').prop('disabled', true);
}
</script>
How about this?
onclick="this.style.visibility='hidden';"
I would say, instead of disabled, hide it.
If you want to go with disabled
onclick="this.style.disabled='true';"
Got an issue on Chrome, wasn't submitting the form. Tried a bunch of different code, this was what worked best for me (and looks best imo):
$('#form_id').submit(function() {
$("input[type='submit']", this)
.val("Please Wait...")
.attr('disabled', 'disabled');
return true;
});
Replace form_id with the id of your form. Classes work too of course: $('.form_class')
Source: JavaScript Coder
I like this better:
<script>
var submit = false;
$('form').submit(function () {
if (submit) { return false; }
else { submit = true;}
});
</script>
this way it also prevents the enter key to submit more than once
I'm using Chrome. Any idea on why I have this problem?
Well, first time I dealt with this, I solved it like this:
function blockButtons() {
$('button:submit').click(function(){
$('button:submit').attr("disabled", true);
});
}
This worked perfectly, but... in Mozilla Firefox. The Google Chrome did not submit it, so I changed it to this:
function blockButtons() {
$('button:submit').click(function(){
var form = $(this).parents('form:first');
$('button:submit').attr("disabled", true);
$('button:submit').css('opacity', 0.5);
form.submit();
});
}
This worked both in Mozilla Firefox, however, after that some of our users using old versions of IE experienced trouble of having two submits. That is, the one initiated by the javascript, and the one by browser ignoring the fact of onclick and just submitting anyway. This can be fixed by e.preventDefault, I guess.
If you don't want an element to be double-clicked, use .one()
<button id="submit" type="submit">Send</button>
<script>
$(function () {
$("#submit").one("click", function () {
//enter your submit code
});
});
.one()
You can do something like this. It is work fine with me.
$("button#submitted").click(function () {
$("button#submitted").prop('disabled', true);
});
Double click on your button. This code will running
You must prevent the form from being submitted more than once, disabling the button is not the right solution because the form could be submitted in other ways.
JavaScript:
$('form').submit(function(e) {
// if the form is disabled don't allow submit
if ($(this).hasClass('disabled')) {
e.preventDefault();
return;
}
$(this).addClass('disabled');
});
Once the form is correctly disabled, you can customize its appearance.
CSS:
form.disabled {
pointer-events: none;
opacity: 0.7;
}
I have the following function to show a alert when the visitor hits "cancel" or trying to go back with filled textfields. The function works perfectly overall but not when I'm hit submit. The alert shows when I hit the button and I don't want it that way.
var changed_flag = 0;
$('input').change(function() {
changed_flag = 1;
});
window.onbeforeunload = function() {
if(changed_flag) {
return 'You haven't saved your work!'
}
};
I know I should edit the $('input').change(... and add input[type="submit"] but I don't know how and where. Do anyone know how I can fix this problem?
Thanks in advance.
Try
$('form').submit(function() {
changed_flag = 0;
});
$('form').submit(function() {
$(window).unbind('beforeunload');
});
Alternatively instead of the unbind you could just do changed_flag = 0
Just have your submit button remove the event or set changed_flag back to 0.
<input type="submit" onmousedown="changed_flag = 0" />
EDIT: On second thoughts put this code in your onsubmit handler in case the form is submitted some other way (like pressing enter or via another function).