Alkahest my heroes have always died at the end

April 18, 2007

Javascript and Form Saves

Filed under: Technical — cec @ 6:06 am

As I’ve been working on the web front end for the PWC database, we ran into an interesting problem. Our patient records are implemented w/ a “tab” style for the display of different parts of the record. Unfortunately, the folks using the database kept tabbing over to a different part of the record which wound up not saving any of the changes they made. My original quick fix for this was to have the tab buttons also save. But that made me nervous. I worried that if someone accidentally changed things or if I was giving a demo, a change to a new tab would save bad data.

I probably could have fixed this with some javascript so that all of the tabs were really part of the same webpage and they would be dynamically hidden or displayed using javascript to manipulate the CSS classes. But that didn’t occur to me until just now. Instead, I implemented a system to note changes in the form and alert if you navigated off the form without saving. Just as a reminder to myself, here’s what I did.

1. Create a confirm_exit.js file with the following:

var needToConfirm = false;
var fieldsChanged = “”;

window.onbeforeunload = confirmExit;

function confirmExit()
{
if (needToConfirm)
{
return “The following fields have changed and are not saved:\n” + fieldsChanged;
}
}

function fieldChanged(fieldName)
{
needToConfirm = true;
fieldsChanged = fieldsChanged + ” ” + fieldName + “\n”;
}

When the script loads, it creates two new variables: needToConfirm and fieldsChanged. needToConfirm starts as false, meaning no need to prompt the user before leaving the page. fieldsChanged is empty since nothing has changed. I also set a trigger on the window: onBeforeUnload, which occurs any time the page is about to be unloaded. For example, close the browser, navigate to a new page, etc. This trigger sends you to the confirmExit function.

2. This is loaded into any webpage that has a form I care about

3. Each form element needs to have an onChange trigger: onChange=”fieldChanged(‘descriptor’);” When the form element changes, the function is called. We set needToConfirm to be true and update the list of fields changed in the form with the descriptor.

4. Finally, we bless the save buttons on the form page by adding an onClick trigger: onClick=”needToConfirm=false;” Having needToConfirm as false prevents the confirmExit() function from prompting the user when they hit the save button.

Voila! Forms that prompt you to save before leaving.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress