Left Navigation Validation - javascript

I have a master page in which leftnavigation.jsp and header.jsp are present.Now leftnavigation contains hyperlinks to few of the webpages(say general.jsp, contact.jsp).On clicking these hyperlinks , these webpages gets opened.like if i click general link, it gets opened, and if i click the link of contact.jsp , contact webpage gets opened.Now these webpages have validations on the save button at the end of the form .
Now i want to have these validation (every webpage has a validation function on save button)to work when a user clicks a link on the left navigation to change the webpage.
The leftnavigation.jsp does not contain any form element. it just contains links or scripplets
any suggestions?

Sounds simple enough. You could make the navigation bar links call the validation function for the forms when clicked. Something like this perhaps:
<a href="anotherpage.jsp" onclick="validate(); return true;>Click me!</a>
Just a warning though: it's impossible to guarantee validation in this manner, users could bypass the validation (the user could click a back button for example). If this is what you're trying to achieve, consider running a validate function onpropertychanged or onkeyup. And, as always, form validations should (almost) never be a hinderance; don't show alert messages or do anything REALLY distracting if a user doesn't type something right.
Notice how the code above would let the user change pages regardless of the form's validation status. You could make the onclick function return false if the form failed validation, but this can be bypassed, and it is a hinderance to users.
If this is really necessary, have the links work regardless, but show a small message, possibly in the form of a div quietly pop up at the top of the page warning the user that one of their form entries was incorrect.

Listen for a click event on your navigation links then run your validation function:
function listen(event, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(event, func, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + event, func);
}
}
var links = document.getElementsByTagName('a');
listen('click', links, validationFunction);
If you're passing in variables, then wrap your validate function in an anonymous function:
listen('click', links, function(param) { validationFunction(param); });

Related

How can I warn user on back button click?

www.example.com/templates/create-template
I want to warn users if they leave create-template page. I mean whether they go to another page or to templates.
I use this code to warn users on a page reload and route changes should the form be dirty.
function preventPageReload() {
var warningMessage = 'Changes you made may not be saved';
if (ctrl.templateForm.$dirty && !confirm(warningMessage)) {
return false
}
}
$transitions.onStart({}, preventPageReload);
window.onbeforeunload = preventPageReload
It works as expected on a page reload and route changes if it is done by clicking on the menu or if you manually change it. However, when I click the back button, it does not fire the warning. only it does if I click the back button for the second time, reload the page, or change route manually.
I am using ui-router. When you click back button, you go from app.templates.create-template state to app.templates state.
How to warn if they press Back button?
First of all, you are using it wrong:
from https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload:
Note: To combat unwanted pop-ups, some browsers don't display prompts
created in beforeunload event handlers unless the page has been interacted
with; some don't display them at all. For a list of specific browsers, see the
Browser_compatibility section.
and
window.onbeforeunload = funcRef
funcRef is a reference to a function or a function expression.
The function should assign a string value to the returnValue property of the Event object and return the same string.
You cannot open any dialogs in onbeforeunload.
Because you don't need a confirm dialog with onbeforeunload. The browser will do that for you if the function returns a value other than null or undefined when you try to leave the page.
Now, as long as you are on the same page, onbeforeunload will not fire because technically you are still on the same page. In that case, you will need some function that fires before the state change where you can put your confirm dialog.
How you do that depends on the router that you are using. I am using ui-router in my current project and I have that check in the uiCanExit function.
Edit:
You can keep your preventPageReload for state changes in angular. But you need a different function for when the user enters a new address or tries to leave the page via link etc.
Example:
window.onbeforeunload = function(e) {
if (ctrl.templateForm.$dirty) {
// note that most broswer will not display this message, but a builtin one instead
var message = 'You have unsaved changes. Do you really want to leave the site?';
e.returnValue = message;
return message;
}
}
However, you can use this as below:(using $transitions)
$transitions.onBefore({}, function(transition) {
return confirm("Are you sure you want to leave this page?");
});
Use $transitions.onBefore insteadof $transitions.onStart.
Hope this may help you. I haven't tested the solutions. This one also can help you.

Confirm redirection from page in javascript

i am working on asp.net site that contains say three pages
page1.aspx
page2.aspx and page3.aspx
I want if user redirects from page1, alert box asking for confirmation should come. For this i have written following code
window.onbeforeunload = function () {
return 'Are you sure you want to leave?';
};
But this code run on every postback to server including pressing F5.
I want this code to run only when user redirects to any of remaining two pages
how can do this ??
try this code in javascript onload event in the pages only
if(confirm("Are you sure you want to leave?"))
{
//redirect to next page
return false
}
Handling in window.onbeforeunload may not be the straight forward way to do it since the alert message will be shown each and every time you load the page.
What you could do instead is call the confirmation js function in the from the DOM object that could possibly take the user to the different page.
For instance, let us suppose the below anchor tag takes the user to page two:
<a id="pageTwoAnchorTag" runat="server" href="~/Page2.aspx">Page 2</a>
you could add the below onclick event to get your confirmation when the user wants to go the page 2:
<a id="pageTwoAnchorTag" runat="server" onclick="return confirm('Are you sure you want to leave?')" href="~/Page2.aspx">Leave Records</a>
Only asking for confirmation in a couple of places might not be fully satisfying, since it will not trigger in all desired cases. For example, when you close the browser tab or window, your data will be lost.
I suggest to do the opposite: Register for the onbeforeunload as you already do, but include a "guard" which you disable on any action that should not trigger the confirmation (i.e. in postbacks):
window.shouldconfirm = true;
window.onbeforeunload = function () {
if (shouldconfirm) {
return 'Are you sure you want to leave?';
}
};
Register for the events that occur before a postback is executed (e.g. button click events, etc.) In those places, disable the confirmation:
window.shouldconfirm = false;
I am slightly surprised that the postbacks trigger the onbeforeunload event. I though to remember that on form posting the event is not triggered, and that a ASP.NET postback is implemented as a form post action.

jquery dirty record, would like the jquery ui modal

I'm using this to test if a form is dirty.
It defaults to the standard browser confirmation asking if you are sure you want to navigate away from this page. On the jquery dirtyforms site it has a section that says you can use the jquery ui modal form.
So I tried adding a section (a div) like so:
<div id="unsavedChanges" title="Save Changes?">
<p>You've made changes to this page. Do you want to leave this page without saving?</p>
</div>
And then I added what their code looked like:
$.DirtyForms.dialog = {
selector: '#unsavedChanges',
fire: function(message, dlgTitle) {
$('#unsavedChanges').dialog({ title: dlgTitle, width: 350, modal: true });
$('#unsavedChanges').html(message);
},
bind: function() {
$('#unsavedChanges').dialog('option', 'buttons',
[
{
text: "Stay Here",
click: function(e) {
$.DirtyForms.choiceContinue = false;
$(this).dialog('close');
}
},
{
text: "Leave This Page",
click: function(e) {
$.DirtyForms.choiceContinue = true;
$(this).dialog('close');
}
}
]
).bind('dialogclose', function(e) {
// Execute the choice after the modal dialog closes
$.DirtyForms.choiceCommit(e);
});
},
refire: function(content) {
return false;
},
stash: function() {
return false;
}
};
Although I am not sure where they want me to place that (I originally placed it outside of document.ready. However, after running this and making a change to my form and navigating away I see that it still is using the browser confirmation instead of jquery ui dialog box. What am I doing wrong here?
You can only popup a custom dialog if the user is trying to leave by clicking an anchor or other element on your page.
Then you could just intercept the click on all anchors etc, prevent it, pop up a custom dialog to confirm. In other words, when someone is clicking an element on your page, you're in control and can do pretty much whatever you want.
However, when the user is trying to leave by closing the tab or browser, you can not stop them with javascript, as it would be extraordinary annoying if websites could do that.
The only way to prompt a user that is leaving by closing the tab/browser window is to use the onbeforeunload event, and that event can only be used with the native confirm dialog, there is no way to use a custom dialog or stop the user or do anything else really, as that could lead to certain websites creating systems where you could never really leave the site.
From the README:
Dirty Forms will alert a user when they attempt to leave a page without submitting a form they have entered data into. It alerts them in a modal popup box, and also falls back to the browser's default onBeforeUnload handler for events outside the scope of the document such as, but not limited to, page refreshes and browser navigation buttons.
(emphasis mine)
If you want to show a modal for this kind of things, well, you simply can't. (The reason why is security: it's easy to imagine a page preventing the user to close it whatever they attempt, short of killing the browser instance.)
Additionally, the "but not limited to" bit is intriguing: I would ask the plugin's author for details on what exactly this covers, as it might overlap with your use-case.

Stealing the redirect URL of a button

Is it possibe to change the return URL of a button whose job is submitting a form to the server? The main deal here is that I don't have the script that controls the button, hence the word "stealing."
If you are curious about the use case, I have a Salesforce Visualforce page that has an embedded Flow in it. I want to jump out of the Flow when the user is half way through and a certain condition is met.
Assuming the button is not in an iFrame...
$('#some_button').click(function (e) {
e.preventDefault();
// Do stuff here then submit the form..
$('#some_form').submit();
});
You could also use this method for $('#some_form').submit().... You can read more about it here.

How to implement a isDirty flag onLeave for a single page application?

I have a single page application written in MVC4 that uses pjax() to push html into various s in my page. I have one sub-form that allows the user to edit the data and it if the user changes the data an isDirty flag gets set in javascript to trigger an alert at the bottom of the page that there are un-saved updates. I would also like to implement an additional warning when the user tries to leave the page without saving. If I use a traditional onbeforeunload function like this
window.onbeforeunload = function() {
if (isDirty) {
return 'You have unsaved changes!';
}
return null;
};
it calls the alert if I try to close the page or navigate away from the site entirely but if the user clicks on one of my links that re-populates the with some different information it does not trigger because you are not actually leaving the page. How can I architect it so that one of these pjax() links causes an alert similar to if I close the page?
You could subscribe to a global event that fires before a pjax request:
$(document).on('pjax:beforeSend', function() {
if (isDirty) {
return confirm('You have unsaved changes! Are you sure you want to continue?');
}
return true;
});
You could add a delegated event handler onto the links in the page. You just have to make sure the handler is bound to links that may load a "new page".

Categories

Resources