/    Sign up×
Community /Pin to ProfileBookmark

Check for changed form fields (scalable solution needed)

Hi!

I’m wondering if anyone here has a suggestion on checking for form fields that have changed.

I have a sample script which works but only for a specific number of fields and field names. Basically I need this script to work with any form name, any number of fields. E.g. Form A has 5 fields, and Form B has 10 fields

The script I’m working with is below. Any suggestions on a way to make this more flexible and scalable would be much appreciated.

var ids = new Array(‘name’, ‘gender’, ‘sendEmail’, ‘radVanilla’, ‘radChocolate’, ‘radStrawberry’);

var values = new Array(”, ”, ”, ”, ”, ”);

function populateArrays()
{
// assign the default values to the items in the values array
for (var i = 0; i < ids.length; i++)
{
var elem = document.getElementById(ids[i]);
if (elem)
if (elem.type == ‘checkbox’ || elem.type == ‘radio’)
values[i] = elem.checked;
else
values[i] = elem.value;
}

}

var needToConfirm = true;

window.onbeforeunload = confirmExit;
function confirmExit()
{
if (needToConfirm)
{
// check to see if any changes to the data entry fields have been made
for (var i = 0; i < values.length; i++)
{
var elem = document.getElementById(ids[i]);
if (elem)
if ((elem.type == ‘checkbox’ || elem.type == ‘radio’)
&& values[i] != elem.checked)
return “Your changes have not been saved. Are you sure you wish to leave this page?”;
else if (!(elem.type == ‘checkbox’ || elem.type == ‘radio’) &&
elem.value != values[i])
return “Your changes have not been saved. Are you sure you wish to leave this page?”;
}

// no changes – return nothing
}

}
</script>

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @gfunk76 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...