I authored an article a few weeks back on a technique for stopping users from leaving a web form if they’ve made changes using JavaScript and the Prototype library. There was one fatal flaw in this otherwise successful script: it only checked for changes in text fields. Well, if you were as frustrated as I was, today’s your lucky day. Read on.
First, let me say if you haven’t read that article, do so now. If you have already, continue. Remember we started with a simple but obtrusive “halt!”? The code looks like this:
var needToConfirm = true;
window.onbeforeunload = confirmExit;
function confirmExit() {
if (needToConfirm)
return "Are you sure you want to leave?";
}
We modified the above to handle many more fields, and to compare arrays using a combination of functions afforded to us by Prototype, 4Guys, and others. You should view/download the full script to see what I’m talking about. All this excitement is of course about how this script can now process (check, compare, validate) all the fields on any form. When I discovered this I slapped myself on my forehead like those new TV commercials for V8. Doh! It’s easy:
On line 4, replace this:
var f = $$('div#myform input');
with this:
var f = $$('form#id input','form#id select');
Replace “#id” with your form’s Id. Using Prototype’s utility function, this creates an array of all the form fields and hands it off to our script… ultimately stopping a user if they made a change to any values, and letting them go if they have had a view-only session.
Editor’s note: The previous version of this script was downloaded a ton of times. I’m assuming folks are using it, and I’m positive there are ways to improve it. Comment away!












No comments
Jump to comment form | Comments RSS | Trackback URI