Don't show onbeforeunload alert when hitting submit - javascript

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).

Related

Javascript or jQuery popup when user click links other than Submit button

I have created a form where user can create his profile, now I want that if user do not click on save/submit button on the page and clicks on any other available link other than save.
Then he should get confirm popup of JavaScript mentioning that you are aborting the creation of profile. I am unable to find any event via which I can achieve this.
Other links are navigation links available on my page.
If you are using button for submit and others as a link then you can find out like this:
$(document).ready(function() {
$(document).('on','click',function(){
var pressedButton = $(this).text();
if(pressedButon == "Submit" || pressedButton =="Save")
{
return false;
}
else
{
$("a").on('click',function() {
var confirmAns = confirm('Your message');
if(confirmAns == true)
{
// DO whatever you want...
}
else
{
//Do whatever you want...
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use onblur event for it and you can achieve your goal. So when a user click anywhere in your web page then the onblur event automatically fire.
You should use onblur event on your save/submit button.
<button onblur="myFunction()" type="button">Save</button>
<script>
function myFunction() {
var txt;
var r = confirm("You are aborting the creation of profile");
if (r == true) {
return true;
} else {
return false;
}
}
</script>
Try using some plugin. There is one jQuery plugin "Are You Sure"
So you just need below code snippet
$('form').areYouSure();
// OR
$('form.my_form_class').areYouSure();
There are some advanced option available with plugin. Checkout its documentation.
If I understood right, you want this two possibilities:
1.User clicks submit button: form gets submitted
2.User clicks "a" link: get alert asking for confirmation to leave the registration process.
First point will be done automatically as it's a form submit button without the need of extra jQuery.
Second point would just need the following code in order to show the confirmation button:
<script>
$(document).ready(function(){
$('a').on('click',function(e){
if (!confirm("Are you sure you want to exit the registration process?")){
e.preventDefault();
return false;
}
});
});
</script>

Submit Form-data after delay, on hitting a submit-button?

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/

fire jquery focus out when only the input focus is changed

I use the following code to add the selected div value into a input.
var lastFocus;
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
//addOrRemoveWatermark(lastFocus);
$(lastFocus).val($(lastFocus).val() + $(this).children('span').html());
});
$('.del').click(function(e){
e.preventDefault();
e.stopPropagation();
//addOrRemoveWatermark(lastFocus);
$(lastFocus).val(function(index, text){
return text.replace(/(\s+)?.$/, '');
});
})
below is a sample image if the input panel I have! This is developed for a touch device and hence the key pad.
The script works fine to add value on each button press in the keypad. The problem I'm facing is for the room number I want to run an ajax call after the user has entered the amount. But since the focus is removed every button click, how can I run the script when the focus is changed to another input. I tried the jquery .focusout() method but it gets fired each and every time the user clicks on a number button.
if anyone can suggest me a work around that would be a great help!
thank you!
Perhaps you could delay the request with something like the following:
var roomNoChanged = false;
$('#room-number').change(function() {
roomNoChanged = true;
});
$('#table-number, #no-of-guests').focus(function() {
if(roomNoChanged) {
roomNoChanged = false;
$.post(...)
}
});

Preventing multiple clicks on button

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});

jQuery confirm button not in a popup confirm() dialog

I have a long form that I am validating with the jQuery validate plugin. After the form validates, I want the submit button to change into a confirm button with an appropriate message above about checking the form for errors. This button, when clicked again, should submit the form for real this time as long as all the required fields are still filled in.
I have the following:
var confirmed = function(){
alert($("#someForm").attr("name")); //just to see the function fire...
$("#someForm").submit();
return true;
}
$(document).ready(function(){
$("#someForm").validate({
submitHandler: function(form){
var oldBtn = $("#submit");
var newBtn = oldBtn.clone();
newBtn.click(confirmed)
newBtn.text("Confirm");
newBtn.insertBefore(oldBtn);
oldBtn.remove();
newBtn.attr({"id": "submit"});
}
});
});
...
<button type="submit" id="submit">Submit</button>
It works to validate the form, then the button changes text, the the function fires (the alert has the name of the form in it) when clicked, but the form never submits for real.
Any help or ideas would be greatly appreciated.
Thanks
EDIT:
Ok, I think I have figured it out. I have the submit button hidden and a button called Validate that just checks if the form is validated without submitting using $("#someForm").valid(); If it checks out, I hide the "Submit" button and show the "Confirm" button along with a little message about checking your submission, etc. See below:
$(document).ready(function(){
$("#submitBtn").hide();
$("#confMessage").hide();
$("#someForm").validate();
});
var checkValid = function(){
var isValid = $("#volunteer").valid();
if(isValid){
$("#validBtn").remove();
$("#submitBtn").show();
$("#confMessage").show();
}
}
...
<p id="confMessage">Please review your submission.</p>
<p><button id="validBtn" onclick="checkValid()">Validate</button>
<button type="submit" id="submitBtn">Submit</button></p>
Works perfectly, and is a heck of a lot cleaner than my original code!
remove oldBtn.remove(); then it will work.
You have
var oldBtn = $("#submit");
var newBtn = oldBtn.clone();
What above line doing is adding same DOM in html so that mean ID will be copied too.
And ID must be unique for each DOM.
Try to rewrite ID for cloned DOM and try.
AND
newBtn.click(confirmed)
This code means you are assigning event to newBtn not calling click event.
For call a click event use .trigger()

Categories

Resources