jQuery: Confirmation dialog before leaving a page while in editing mode - javascript

I try to appear a message when the user edit some field and try to go to another page or click close to the page
message appear
This page is asking you to confirm that you want to leave - data you have entered may not be saved.
I use this code :
$('#form').data('serialize',$('#form').serialize());
// On load save form current state
$(window).bind('beforeunload', function(e){
if($('#form').serialize()!=$('#form').data('serialize'))return true;
else e=null;
// i.e; if form state change show box not.
});
This code works only when the user try to edit something if not I can close the page and thats what I want.
The problem is that the message appear also when I submit the form
When I try to click the button submit the message appear also
This page is asking you to confirm that you want to leave - data you have entered may not be saved.
How to prevent to show that message when I click the submit button ??!!

Save the listener in a variable and remove it on submit
const onBeforeUnloadListener function(e){
if($('#form').serialize()!=$('#form').data('serialize'))return true;
else e=null;
// i.e; if form state change show box not.
}
$(window).bind('beforeunload', onBeforeUnloadListener);
$('#form').on('submit', function() {
$(window).unbind('beforeunload', onBeforeUnloadListener)
}

Related

JS how to force user to click a link in a form

I have a html form with multiple form elements as well as a link inside the form that opens to a website. I create a Javascript overall form validation to validate elements in the form as well as the link as I would want to enforce user to have to click on the link if not the form will not go through when user clicks submit button. Moreover, when user clicks on the button to submit info in the form but does not click on the link, I would want to remind user to click in the link. I create a modal drop down validation alert to remind user to click on the link but I struggle to find the JS validation logic to alert user to click on the link before click the submit button. Any help is appreciated. Below is my JS code for validation.
//Approach 1
function validation_modal(){
$(".form-modal").modal("show");
}
function validation_form(){
$(document).off("click", "a", function() {
var href = $(this).attr("href");
if(href !== "https://www.../")
{
$(".modalNote").text("Please click on the link");
validation_modal();
return false;
}
})
...other elements in form validation
}
// Approach 2
function validation_modal(){
$(".form-modal").modal("show");
}
function validation form() {
$(document).on("click", "a", function() {
var href = $(this).attr("href");
if(href !== "https://www...")
{
$(".modalNote").text("Please click on the link");
validation_modal();
return false;
}
})
...other elements in the form validation
}
Both of my above logic has either not work and not achieve what I would want to do. Thank you for your help.
Below is the html code for the link in the form
<div class="row row-label c_5" id="sec5_div" "><br>
Department Request Form
</div><br>
This is a user request as the link opens to another form which has to be filled out and submit before the main form.

Narrow Down BeforeUnload To Only Fire If Field Is Changed or Updated

I am trying to figure out how to limit the beforeunload command on my form. I have been able to figure out how to unbind the beforeunload command and then when I go to navigate away from the form this works. However, the unload happens every time regardless of whether or not the form was changed. I'm trying to figure out how to get the beforeunload to only fire if the form was actually updated or changed. If the user clicks the back button on the browser, the beforeunload does not fire. This is perfect. However, if the user clicks on a link on the "form" it pops up the beforeunload prompt. Is this as designed? Perhaps I should be approaching this differently? I'm a newbie..so I'm open to suggestions.
I have read through the MDN link that explains beforeunload...https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
and can't seem to figure out how to narrow down the beforeunload to only if a field on the form has been changed.
$('form').submit(function() {
$(window).unbind('beforeunload');
});
$(window).on('beforeunload',function(){
return '';
});
I am trying to figure out how to alter the code above so that the beforeunload only fires if a field on my form changes when the user goes to navigate away from this page. It's confusing for the user if there is a pop up asking if they want to navigate away from the page if nothing has been clicked or changed.
Something like this.
We check out simple form and only prompt user if there is a value.
Added variable set when submitting, this allows us to bypass our onunload tests.
var submitting = false;
window.addEventListener("beforeunload", function (event) {
console.log('checking form');
let inputValue = document.querySelector('#myInput').value;
if(inputValue.length > 0 && submitting === false) {
console.log(inputValue);
event.returnValue = 'Are you sure you wish to leave?';
}
event.preventDefault();
});
document.addEventListener("submit", function(event) {
submitting = true;
});
<form submit="somewhere.htm">
<input id="myInput" type="text" />
<input type="submit" value="Submit">
</form>
Test navigate away

Changing type on element is not possible twice?

I'm relying on another plugins javascript that has code for a specific submit event that submits the form after some validation.
I'm not able to change that validation without hacking into that code.
Therefore I've came up with a hack without hacking into that plugin's code.
I'm changing the input type from submit to button type so I can do my own validation without having to take in account for action that is triggered upon submit.
There are two radiobuttons with class .give-gateway. Basically I'm doing this.
HTML (element in form):
<input type="submit" class="give-submit give-btn" id="give-purchase-button"
name="give-purchase" value="Donate Now" data-before-validation-label="Donate
Now">
jQuery:
$('body').on('click', '.give-gateway', check_gateway);
function check_gateway(id) {
//Value from which radiobutton is selected
if (current_gateway == 'swish') {
alert('changing button from ORIGINAL to new. NOW IT SHOULD BE
TYPE BUTTON!!!');
$('#give-purchase-button').prop('id', 'give-purchase-button-
new').prop('type','button');
$('body').on('click touchend', '#give-purchase-button-new', function
(e) {
alert('NEW give purchase button clicked');
//some code...
});
}
else {
alert('changing button from NEW to original. NOW IT SHOULD BE TYPE
SUBMIT!!!');
$('#give-purchase-button-new').attr('id', 'give-purchase-
button').prop('type','submit');
}
}
This works the first time:
From Submit to button
From Button to Submit
From Submit to Button
Step 3 (NOT WORKING (first click on swish gateway work but second time it does not change from submit to button)!? **Why?) **
I've also tried to programmatically add onsubmit to form but the issue there is that other plugins jquery code has a listener for click event on the actual submit - button which means that that code are executed first anyway. I don't want that to happen.
I've figured it out why now. When I click on another gateway the form is loaded with other content. When I go from swish to paypal. It loads content that is dependent of paypal stuff and creates a new submit - button. If I just change from type submit to button it does not affect anything because that change is made before the actual content is loaded (through ajax) and therefore creates a new submit button.

How do I add jQuery to a submit button which fires before Paypal objects?

I have a Paypal Digital Express form which works fine. However, I would like to add a bit of jQuery to the submit button which will fire -before- the Paypal popup window opens and can prevent the Paypal code from firing. Unfortunately, the Paypal window always open first.
jQuery('#buyLink').click( function(e) {
e.preventDefault();
// if no boxes are checked; no songs selected
if ( jQuery("#buysongs input:checkbox:checked").length == 0) {
alert('Please select at least one song!');
return false;
}
});
Is there a way to prioritise my code so that it fires -before- the Paypal code?
EDIT: I added e.preventDefault() per the first answer, but what that does is:
a) the popup window still opens but
b) the Paypal site is never reached.
Instead, it displays the calling page in the popup.
So... I want to prevent that Paypal popup window from opening. Perhaps I need to change the 'action' on the form and trigger that action from inside my jQuery? If so, how do I do this?
Look into the preventDefault() function:
jQuery('#buyLink').click( function(event) {
event.preventDefault();
if (jQuery("#buysongs input:checkbox:checked").length == 0) {
alert('Please select at least one song!');
return false;
}
else{
// submit form
}
});

How to validate the hyper link and checkbox when submit button is clicked

we have a submit button with a checkbox and a hyper link in a view in mvc 3. we need validate both the check box and the hyper link on the click of the submit button.
For eaxmple in case the checkbox is not checked and the user hits the submit we need to show the error message "please check the checkbox".
in case if the checkbox is checked and the hyper link is not clicked by the user we need to show the error message "Please click the link".
how to solve this senario using jquery and mvc 3?
You need to have a way to keep track of the clicked action for the hyperlink on the client side. If you wish to keep track of it on the server then that's another thing. So suppose your hyperlink has an id Link1 and the checkbox has an id AcceptMe. You can do something like
<script>
var isLinkClicked = false;
$(function() {
$("Link1").click(function() {
isLinkClicked = true;
});
$("#submitButtonId").click(function(){
if (!isLinkClicked) {
alert("Please click the link"); // or show it somewhere
return;
}
if (!$("#AcceptMe").is(":checked")) {
alert("Please check the checkbox"); // or show it somewhere
return;
}
// else submit your form
});
});
</script>

Categories