Problem statement:
It is necessary for me to write a code, whether which before form sending will check all necessary fields are filled. If not all fields are filled, it is necessary to allocate with their red colour and not to send the form.
Now the code exists in such kind:
function formsubmit(formName, reqFieldArr){
var curForm = new formObj(formName, reqFieldArr);
if(curForm.valid)
curForm.send();
else
curForm.paint();
}
function formObj(formName, reqFieldArr){
var filledCount = 0;
var fieldArr = new Array();
for(i=reqFieldArr.length-1; i>=0; i--){
fieldArr[i] = new fieldObj(formName, reqFieldArr[i]);
if(fieldArr[i].filled == true)
filledCount++;
}
if(filledCount == fieldArr.length)
this.valid = true;
else
this.valid = false;
this.paint = function(){
for(i=fieldArr.length-1; i>=0; i--){
if(fieldArr[i].filled == false)
fieldArr[i].paintInRed();
else
fieldArr[i].unPaintInRed();
}
}
this.send = function(){
document.forms[formName].submit();
}
}
function fieldObj(formName, fName){
var curField = document.forms[formName].elements[fName];
if(curField.value != '')
this.filled = true;
else
this.filled = false;
this.paintInRed = function(){
curField.addClassName('red');
}
this.unPaintInRed = function(){
curField.removeClassName('red');
}
}
Function is caused in such a way:
<input type="button" onClick="formsubmit('orderform', ['name', 'post', 'payer', 'recipient', 'good'])" value="send" />
Now the code works. But I would like to add "dynamism" in it.
That it is necessary for me: to keep an initial code essentially, to add listening form fields (only necessary for filling).
For example, when the field is allocated by red colour and the user starts it to fill, it should become white.
As a matter of fact I need to add listening of events: onChange, blur for the blank fields of the form. As it to make within the limits of an initial code.
If all my code - full nonsense, let me know about it. As to me it to change using object-oriented the approach.
Give me pure Javascript solution, please. Jquery - great lib, but it does not approach for me.
To keep your HTML clean, I suggest a slightly different strategy.
Use a framework like jQuery which makes a lot of things much more simple.
Move all the code into an external script.
Use the body.onLoad event to look up all forms and install the checking code.
Instead of hardcoding the field values, add a css class to each field that is required:
<input type="text" ... class="textField required" ...>
Note that you can have more than a single class.
When the form is submitted, examine all fields and check that all with the class required are non-empty. If they are empty, add the class error otherwise remove this class. Also consider to add a tooltip which says "Field is required" or, even better, add this text next to the field so the user can see with a single glance what is wrong.
In the CSS stylesheet, you can then define a rule how to display errors.
For the rest of the functionaly, check the jQuery docs about form events.
Has made.
function formsubmit(formName, reqFieldArr){
var curForm = new formObj(formName, reqFieldArr);
if(curForm.valid)
curForm.send();
else{
curForm.paint();
curForm.listen();
}
}
function formObj(formName, reqFieldArr){
var filledCount = 0;
var fieldArr = new Array();
for(i=reqFieldArr.length-1; i>=0; i--){
fieldArr[i] = new fieldObj(formName, reqFieldArr[i]);
if(fieldArr[i].filled == true)
filledCount++;
}
if(filledCount == fieldArr.length)
this.valid = true;
else
this.valid = false;
this.paint = function(){
for(i=fieldArr.length-1; i>=0; i--){
if(fieldArr[i].filled == false)
fieldArr[i].paintInRed();
else
fieldArr[i].unPaintInRed();
}
}
this.send = function(){
document.forms[formName].submit();
}
this.listen = function(){
for(i=fieldArr.length-1; i>=0; i--){
fieldArr[i].fieldListen();
}
}
}
function fieldObj(formName, fName){
var curField = document.forms[formName].elements[fName];
this.filled = getValueBool();
this.paintInRed = function(){
curField.addClassName('red');
}
this.unPaintInRed = function(){
curField.removeClassName('red');
}
this.fieldListen = function(){
curField.onkeyup = function(){
if(curField.value != ''){
curField.removeClassName('red');
}
else{
curField.addClassName('red');
}
}
}
function getValueBool(){
if(curField.value != '')
return true;
else
return false;
}
}
This code is not pleasant to me, but it works also I could not improve it without rewriting completely.
jQuery adds a lot of benefit for a low overhead. It has a validation plugin which is very popular. There are some alternatives as well but I have found jQuery to be the best.
Benefits
small download size
built in cross browser support
vibrant plug-in community
improved productivity
improved user experience
Related
This is my jquery code that I am using to truncate the pasted text, so that it doesn't exceed the maxlength of an element. The default behaviour on Chrome is to check this automatically but in IE 8 and 9 it pastes the whole text and doesn't check the maxLength of an element. Please help me to do this. This is my first time asking a question here, so please let me know if I need to provide some more details. Thanks.
<script type="text/javascript">
//var lenGlobal;
var maxLength;
function doKeypress(control) {
maxLength = control.attributes["maxLength"].value;
value = control.value;
if (maxLength && value.length > maxLength - 1) {
event.returnValue = false;
maxLength = parseInt(maxLength);
}
}
//function doBeforePaste(control) {
//maxLength = control.attributes["maxLength"].value;
//if (maxLength) {
// event.returnValue = false;
//var v = control.value;
//lenGlobal = v.length;
// }
// }
$(document).on("focus","input[type=text],textarea",function(e){
var t = e.target;
maxLength = parseInt($(this).attr('maxLength'));
if(!$(t).data("EventListenerSet")){
//get length of field before paste
var keyup = function(){
$(this).data("lastLength",$(this).val().length);
};
$(t).data("lastLength", $(t).val().length);
//catch paste event
var paste = function(){
$(this).data("paste",1);//Opera 11.11+
};
//process modified data, if paste occured
var func = function(){
if($(this).data("paste")){
var dat = this.value.substr($(this).data("lastLength"));
//alert(this.value.substr($(this).data("lastLength")));
// alert(dat.substr(0,4));
$(this).data("paste",0);
//this.value = this.value.substr(0,$(this).data("lastLength"));
$(t).data("lastLength", $(t).val().length);
if (dat == ""){
this.value = $(t).val();
}
else
{
this.value = dat.substr(0,maxLength);
}
}
};
if(window.addEventListener) {
t.addEventListener('keyup', keyup, false);
t.addEventListener('paste', paste, false);
t.addEventListener('input', func, false);
} else{//IE
t.attachEvent('onkeyup', function() {keyup.call(t);});
t.attachEvent('onpaste', function() {paste.call(t);});
t.attachEvent('onpropertychange', function() {func.call(t);});
}
$(t).data("EventListenerSet",1);
}
});
</script>
You could do something like this, mind you this was done in YUI but something simlar can be done for jquery. All you need to do is get the length of the comment that was entered and then truncate the text down the the desired length which in the case of this example is 2000 characters.
comment_text_box.on('valuechange', function(e) {
//Get the comment the user input
var comment_text = e.currentTarget.get('value');
//Get the comment length
var comment_length = comment_text.length;
if(comment_length > 2000){
alert('The comment entered is ' + comment_length + ' characters long and will be truncated to 2000 characters.');
//Truncate the comment
var new_comment = comment_text.substring(0, 2000);
//Set the value of the textarea to truncated comment
e.currentTarget.set('value', new_comment);
}
});
You're putting too much effort into something that is apparently a browser quirk and is mostly beyond your control and could change in the future. In fact, I can't recreate this in IE10 - it behaves just like Chrome for me.
Make sure you are validating the length on the server-side, since it's still possible to get around a field's maxlength when submitting the form input to the server (see this somewhat similar question). That's not to say you shouldn't have some client-side logic to validate the length of the input to enforce the maxlength constraint - I just think you don't need to go to the length you are attempting here to essentially intercept a paste command. Keep it simple - having a basic length validation check in your JavaScript is going to be a lot less messy than what you have here.
Perhaps consider a bit of jQuery like this:
$("#myTextControl").change(function() {
if ($(this).val().length > $(this).attr('maxlength')) {
DisplayLengthError();
}
});
(where DisplayLengthError() is an arbitrary function that triggers some kind of feedback to the user that they have exceeded the maxlength constraint of the field, be it an error label, and alert box, etc.)
So, I have some faux checkboxes (so I could style them) that work with jQuery to act as checked or not checked. There are a number of faux checkboxes in my document, and for each one I have a click function:
var productInterest = [];
productInterest[0] = false;
productInterest[1] = false;
productInterest[2] = false;
// here is one function of the three:
$('#productOne').click(function() {
if (productInterest[0] == false) {
$(this).addClass("checkboxChecked");
productInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
productInterest[0] = false;
}
});
The problem seems to be that there is an error in the if statement, because it will check, but not uncheck. In other words it will add the class, but the variable won't change so it still thinks its checked. Anybody have any ideas? Thanks for your help.
UPDATE: So, I need to show you all my code because it works in the way I supplied it (thanks commenters for helping me realize that)... just not in the way its actually being used on my site. so below please find the code in its entirety.
Everything needs to happen in one function, because the UI and data for each checkbox need to be updated at once. So here is the complete function:
$('input[name=silkInterest]').click(function() { // they all have the same name
var silkInterest = [];
silkInterest[0] = false;
silkInterest[1] = false;
silkInterest[2] = false;
if ($(this).is('#silkSilk')) { // function stops working because the .is()
if (silkInterest[0] == false) {
$(this).addClass("checkboxChecked");
silkInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[0] = false;
}
alert(silkInterest[0]);
}
if ($(this).is('#silkAlmond')) {
if (silkInterest[1] == false) {
$(this).addClass("checkboxChecked");
silkInterest[1] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[1] = false;
}
}
if ($(this).is('#silkCoconut')) {
if (silkInterest[2] == false) {
$(this).addClass("checkboxChecked");
silkInterest[2] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[2] = false;
}
}
var silkInterestString = silkInterest.toString();
$('input[name=silkInterestAnswer]').val(silkInterestString);
// This last bit puts the code into a hidden field so I can capture it with php.
});
I can't spot the problem in your code, but you can simply use the class you're adding in place of the productInterest array. This lets you condense the code down to a single:
// Condense productOne, productTwo, etc...
$('[id^="product"]').click(function() {
// Condense addClass, removeClass
$(this).toggleClass('checkboxChecked');
});
And to check if one of them is checked:
if ($('#productOne').hasClass('checkboxChecked')) {...}
This'll make sure the UI is always synced to the "data", so if there's other code that's interfering you'll be able to spot it.
Okay, just had a palm to forehead moment. In regards to my revised code- the variables get reset everytime I click. That was the problem. Duh.
I have written a game in java script and while it works, it is slow responding to multiple clicks. Below is a very simplified version of the code that I am using to handle clicks and it is still fails to respond to a second click of 2 if you don't wait long enough. Is this something that I need to just accept or is there a faster way to be ready for the next click?
BTW, I attach this function using AddEvent from the quirksmode recoding contest.
var selected = false;
var z = null;
function handleClicks(evt) {
evt = (evt)?evt:((window.event)?window.event:null);
if (selected) {
z.innerHTML = '<div class="rowbox a">a</div>';
selected = false;
} else {
z.innerHTML = '<div class="rowbox selecteda">a</div>';
selected = true;
}
}
The live code may be seen at http://www.omega-link.com/index.php?content=testgame
You could try to only change the classname instead of removing/adding a div to the DOM (which is what the innerHTML property does).
Something like:
var selected = false;
var z = null;
function handleClicks(evt)
{
var tmp;
if(z == null)
return;
evt = (evt)?evt:((window.event)?window.event:null);
tmp = z.firstChild;
while((tmp != null) && (tmp.tagName != 'DIV'))
tmp = tmp.firstChild;
if(tmp != null)
{
if (selected)
{
tmp.className = "rowbox a";
selected = false;
} else
{
tmp.className = "rowbox selecteda";
selected = true;
}
}
}
I think your problem is that the 2nd click is registering as a dblclick event, not as a click event. The change is happening quickly, but the 2nd click is ignored unless you wait. I would suggest changing to either the mousedown or mouseup event.
I believe your problem is the changing of the innerHTML which changes the DOM which is a huge performance problem.
Yeah you may want to compare the performance of innerHTML against document.createElement() or even:
el.style.display = 'block' // turn off display: none.
Profiling your code may be helpful as you A/B various refactorings:
http://www.mozilla.org/performance/jsprofiler.html
http://developer.yahoo.com/yui/profiler/
http://weblogs.asp.net/stevewellens/archive/2009/03/26/ie-8-can-profile-javascript.aspx
I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The prompt should not display if the user hasn't touched any of the controls.
Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this? Ideally I'd like something that can easily be reused across multiple pages with minimal changes.
Using jQuery:
var _isDirty = false;
$("input[type='text']").change(function(){
_isDirty = true;
});
// replicate for other input types and selects
Combine with onunload/onbeforeunload methods as required.
From the comments, the following references all input fields, without duplicating code:
$(':input').change(function () {
Using $(":input") refers to all input, textarea, select, and button elements.
One piece of the puzzle:
/**
* Determines if a form is dirty by comparing the current value of each element
* with its default value.
*
* #param {Form} form the form to be checked.
* #return {Boolean} <code>true</code> if the form is dirty, <code>false</code>
* otherwise.
*/
function formIsDirty(form) {
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio") {
if (element.checked != element.defaultChecked) {
return true;
}
}
else if (type == "hidden" || type == "password" ||
type == "text" || type == "textarea") {
if (element.value != element.defaultValue) {
return true;
}
}
else if (type == "select-one" || type == "select-multiple") {
for (var j = 0; j < element.options.length; j++) {
if (element.options[j].selected !=
element.options[j].defaultSelected) {
return true;
}
}
}
}
return false;
}
And another:
window.onbeforeunload = function(e) {
e = e || window.event;
if (formIsDirty(document.forms["someForm"])) {
// For IE and Firefox
if (e) {
e.returnValue = "You have unsaved changes.";
}
// For Safari
return "You have unsaved changes.";
}
};
Wrap it all up, and what do you get?
var confirmExitIfModified = (function() {
function formIsDirty(form) {
// ...as above
}
return function(form, message) {
window.onbeforeunload = function(e) {
e = e || window.event;
if (formIsDirty(document.forms[form])) {
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
}
};
};
})();
confirmExitIfModified("someForm", "You have unsaved changes.");
You'll probably also want to change the registration of the beforeunload event handler to use LIBRARY_OF_CHOICE's event registration.
In the .aspx page, you need a Javascript function to tell whether or not the form info is "dirty"
<script language="javascript">
var isDirty = false;
function setDirty() {
isDirty = true;
}
function checkSave() {
var sSave;
if (isDirty == true) {
sSave = window.confirm("You have some changes that have not been saved. Click OK to save now or CANCEL to continue without saving.");
if (sSave == true) {
document.getElementById('__EVENTTARGET').value = 'btnSubmit';
document.getElementById('__EVENTARGUMENT').value = 'Click';
window.document.formName.submit();
} else {
return true;
}
}
}
</script>
<body class="StandardBody" onunload="checkSave()">
and in the codebehind, add the triggers to the input fields as well as resets on the submission/cancel buttons....
btnSubmit.Attributes.Add("onclick", "isDirty = 0;");
btnCancel.Attributes.Add("onclick", "isDirty = 0;");
txtName.Attributes.Add("onchange", "setDirty();");
txtAddress.Attributes.Add("onchange", "setDirty();");
//etc..
The following uses the browser's onbeforeunload function and jquery to capture any onchange event. IT also looks for any submit or reset buttons to reset the flag indicating changes have occurred.
dataChanged = 0; // global variable flags unsaved changes
function bindForChange(){
$('input,checkbox,textarea,radio,select').bind('change',function(event) { dataChanged = 1})
$(':reset,:submit').bind('click',function(event) { dataChanged = 0 })
}
function askConfirm(){
if (dataChanged){
return "You have some unsaved changes. Press OK to continue without saving."
}
}
window.onbeforeunload = askConfirm;
window.onload = bindForChange;
Thanks for the replies everyone. I ended up implementing a solution using JQuery and the Protect-Data plug-in. This allows me to automatically apply monitoring to all controls on a page.
There are a few caveats however, especially when dealing with an ASP .Net application:
When a user chooses the cancel option, the doPostBack function will throw a JavaScript error. I had to manually put a try-catch around the .submit call within doPostBack to suppress it.
On some pages, a user could perform an action that performs a postback to the same page, but isn't a save. This results in any JavaScript logic resetting, so it thinks nothing has changed after the postback when something may have. I had to implement a hidden textbox that gets posted back with the page, and is used to hold a simple boolean value indicating whether the data is dirty. This gets persisted across postbacks.
You may want some postbacks on the page to not trigger the dialog, such as a Save button. In this case, you can use JQuery to add an OnClick function which sets window.onbeforeunload to null.
Hopefully this is helpful for anyone else who has to implement something similar.
General Solution Supporting multiple forms in a given page (Just copy and paste in your project)
$(document).ready(function() {
$('form :input').change(function() {
$(this).closest('form').addClass('form-dirty');
});
$(window).bind('beforeunload', function() {
if($('form:not(.ignore-changes).form-dirty').length > 0) {
return 'You have unsaved changes, are you sure you want to discard them?';
}
});
$('form').bind('submit',function() {
$(this).closest('form').removeClass('form-dirty');
return true;
});
});
Note: This solution is combined from others' solutions to create a general integrated solution.
Features:
Just copy and paste into your app.
Supports Multiple Forms.
You can style or make actions dirty forms, since they've the class "form-dirty".
You can exclude some forms by adding the class 'ignore-changes'.
The following solution works for prototype (tested in FF, IE 6 and Safari). It uses a generic form observer (which fires form:changed when any fields of the form have been modified), which you can use for other stuff as well.
/* use this function to announce changes from your own scripts/event handlers.
* Example: onClick="makeDirty($(this).up('form'));"
*/
function makeDirty(form) {
form.fire("form:changed");
}
function handleChange(form, event) {
makeDirty(form);
}
/* generic form observer, ensure that form:changed is being fired whenever
* a field is being changed in that particular for
*/
function setupFormChangeObserver(form) {
var handler = handleChange.curry(form);
form.getElements().each(function (element) {
element.observe("change", handler);
});
}
/* installs a form protector to a form marked with class 'protectForm' */
function setupProtectForm() {
var form = $$("form.protectForm").first();
/* abort if no form */
if (!form) return;
setupFormChangeObserver(form);
var dirty = false;
form.observe("form:changed", function(event) {
dirty = true;
});
/* submitting the form makes the form clean again */
form.observe("submit", function(event) {
dirty = false;
});
/* unfortunatly a propper event handler doesn't appear to work with IE and Safari */
window.onbeforeunload = function(event) {
if (dirty) {
return "There are unsaved changes, they will be lost if you leave now.";
}
};
}
document.observe("dom:loaded", setupProtectForm);
Here's a javascript / jquery solution that is simple. It accounts for "undos" by the user, it is encapsulated within a function for ease of application, and it doesn't misfire on submit. Just call the function and pass the ID of your form.
This function serializes the form once when the page is loaded, and again before the user leaves the page. If the two form states are different, the prompt is shown.
Try it out: http://jsfiddle.net/skibulk/Ydt7Y/
function formUnloadPrompt(formSelector) {
var formA = $(formSelector).serialize(), formB, formSubmit = false;
// Detect Form Submit
$(formSelector).submit( function(){
formSubmit = true;
});
// Handle Form Unload
window.onbeforeunload = function(){
if (formSubmit) return;
formB = $(formSelector).serialize();
if (formA != formB) return "Your changes have not been saved.";
};
}
$(function(){
formUnloadPrompt('form');
});
I recently contributed to an open source jQuery plugin called dirtyForms.
The plugin is designed to work with dynamically added HTML, supports multiple forms, can support virtually any dialog framework, falls back to the browser beforeunload dialog, has a pluggable helper framework to support getting dirty status from custom editors (a tinyMCE plugin is included), works within iFrames, and the dirty status can be set or reset at will.
https://github.com/snikch/jquery.dirtyforms
Detect form changes with using jQuery is very simple:
var formInitVal = $('#formId').serialize(); // detect form init value after form is displayed
// check for form changes
if ($('#formId').serialize() != formInitVal) {
// show confirmation alert
}
I expanded on Slace's suggestion above, to include most editable elements and also excluding certain elements (with a CSS style called "srSearch" here) from causing the dirty flag to be set.
<script type="text/javascript">
var _isDirty = false;
$(document).ready(function () {
// Set exclude CSS class on radio-button list elements
$('table.srSearch input:radio').addClass("srSearch");
$("input[type='text'],input[type='radio'],select,textarea").not(".srSearch").change(function () {
_isDirty = true;
});
});
$(window).bind('beforeunload', function () {
if (_isDirty) {
return 'You have unsaved changes.';
}
});
var unsaved = false;
$(":input").change(function () {
unsaved = true;
});
function unloadPage() {
if (unsaved) {
alert("You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?");
}
}
window.onbeforeunload = unloadPage;
This is exactly what the Fleegix.js plugin fleegix.form.diff (http://js.fleegix.org/plugins/form/diff) was created for. Serialize the initial state of the form on load using fleegix.form.toObject (http://js.fleegix.org/ref#fleegix.form.toObject) and save it in a variable, then compare with the current state using fleegix.form.diff on unload. Easy as pie.
A lot of outdated answers so here's something a little more modern.
ES6
let dirty = false
document.querySelectorAll('form').forEach(e => e.onchange = () => dirty = true)
One method, using arrays to hold the variables so changes can be tracked.
Here's a very simple method to detect changes, but the rest isn't as elegant.
Another method which is fairly simple and small, from Farfetched Blog:
<body onLoad="lookForChanges()" onBeforeUnload="return warnOfUnsavedChanges()">
<form>
<select name=a multiple>
<option value=1>1
<option value=2>2
<option value=3>3
</select>
<input name=b value=123>
<input type=submit>
</form>
<script>
var changed = 0;
function recordChange() {
changed = 1;
}
function recordChangeIfChangeKey(myevent) {
if (myevent.which && !myevent.ctrlKey && !myevent.ctrlKey)
recordChange(myevent);
}
function ignoreChange() {
changed = 0;
}
function lookForChanges() {
var origfunc;
for (i = 0; i < document.forms.length; i++) {
for (j = 0; j < document.forms[i].elements.length; j++) {
var formField=document.forms[i].elements[j];
var formFieldType=formField.type.toLowerCase();
if (formFieldType == 'checkbox' || formFieldType == 'radio') {
addHandler(formField, 'click', recordChange);
} else if (formFieldType == 'text' || formFieldType == 'textarea') {
if (formField.attachEvent) {
addHandler(formField, 'keypress', recordChange);
} else {
addHandler(formField, 'keypress', recordChangeIfChangeKey);
}
} else if (formFieldType == 'select-multiple' || formFieldType == 'select-one') {
addHandler(formField, 'change', recordChange);
}
}
addHandler(document.forms[i], 'submit', ignoreChange);
}
}
function warnOfUnsavedChanges() {
if (changed) {
if ("event" in window) //ie
event.returnValue = 'You have unsaved changes on this page, which will be discarded if you leave now. Click "Cancel" in order to save them first.';
else //netscape
return false;
}
}
function addHandler(target, eventName, handler) {
if (target.attachEvent) {
target.attachEvent('on'+eventName, handler);
} else {
target.addEventListener(eventName, handler, false);
}
}
</script>
In IE document.ready will not work properly it will update the values of input.
so we need to bind load event inside the document.ready function that will handle for IE browser also.
below is the code you should put inside the document.ready function.
$(document).ready(function () {
$(window).bind("load", function () {
$("input, select").change(function () {});
});
});
I have found that this one works in Chrome with an exception... The messages being returned do not match those in the script:
dataChanged = 0; // global variable flags unsaved changes
function bindForChange() {
$("input,checkbox,textarea,radio,select").bind("change", function (_event) {
dataChanged = 1;
});
$(":reset,:submit").bind("click", function (_event) {
dataChanged = 0;
});
}
function askConfirm() {
if (dataChanged) {
var message =
"You have some unsaved changes. Press OK to continue without saving.";
return message;
}
}
window.onbeforeunload = askConfirm;
window.onload = bindForChange;
The messages returned seem to be triggered by the specific type of action I'm performing. A RELOAD displays a question "Reload Site?
And a windows close returns a "Leave Site?" message.
I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to
enable "save" button only when something has changed
alert if the user wants to close the page and something is not saved
Ideas?
Loop through all the input elements, and put an onchange handler on each. When that fires, set a flag which lets you know the form has changed. A basic version of that would be very easy to set up, but wouldn't be smart enough to recognize if someone changed an input from "a" to "b" and then back to "a". If it were important to catch that case, then it'd still be possible, but would take a bit more work.
Here's a basic example in jQuery:
$("#myForm")
.on("input", function() {
// do whatever you need to do when something's changed.
// perhaps set up an onExit function on the window
$('#saveButton').show();
})
;
Text form elements in JS expose a .value property and a .defaultValue property, so you can easily implement something like:
function formChanged(form) {
for (var i = 0; i < form.elements.length; i++) {
if(form.elements[i].value != form.elements[i].defaultValue) return(true);
}
return(false);
}
For checkboxes and radio buttons see whether element.checked != element.defaultChecked, and for HTML <select /> elements you'll need to loop over the select.options array and check for each option whether selected == defaultSelected.
You might want to look at using a framework like jQuery to attach handlers to the onchange event of each individual form element. These handlers can call your formChanged() code and modify the enabled property of your "save" button, and/or attach/detach an event handler for the document body's beforeunload event.
Here's a javascript & jquery method for detecting form changes that is simple. It disables the submit button until changes are made. It detects attempts to leave the page by means other than submitting the form. It accounts for "undos" by the user, it is encapsulated within a function for ease of application, and it doesn't misfire on submit. Just call the function and pass the ID of your form.
This function serializes the form once when the page is loaded, and again before the user leaves the page. If the two form states are different, the prompt is shown.
Try it out: http://jsfiddle.net/skibulk/ev5rE/
function formUnloadPrompt(formSelector) {
var formA = $(formSelector).serialize(), formB, formSubmit = false;
// Detect Form Submit
$(formSelector).submit( function(){
formSubmit = true;
});
// Handle Form Unload
window.onbeforeunload = function(){
if (formSubmit) return;
formB = $(formSelector).serialize();
if (formA != formB) return "Your changes have not been saved.";
};
// Enable & Disable Submit Button
var formToggleSubmit = function(){
formB = $(formSelector).serialize();
$(formSelector+' [type="submit"]').attr( "disabled", formA == formB);
};
formToggleSubmit();
$(formSelector).change(formToggleSubmit);
$(formSelector).keyup(formToggleSubmit);
}
// Call function on DOM Ready:
$(function(){
formUnloadPrompt('form');
});
Try
function isModifiedForm(form){
var __clone = $(form).clone();
__clone[0].reset();
return $(form).serialize() == $(__clone).serialize();
}
Hope its helps ))
If your using a web app framework (rails, ASP.NET, Cake, symfony), there should be packages for ajax validation,
http://webtecker.com/2008/03/17/list-of-ajax-form-validators/
and some wrapper on onbeforeunload() to warn users taht are about to close the form:
http://pragmatig.wordpress.com/2008/03/03/protecting-userdata-from-beeing-lost-with-jquery/
Detecting Unsaved Changes
I answered a question like this on Ars Technica, but the question was framed such that the changes needed to be detected even if the user does not blur a text field (in which case the change event never fires). I came up with a comprehensive script which:
enables submit and reset buttons if field values change
disables submit and reset buttons if the form is reset
interrupts leaving the page if form data has changed and not been submitted
supports IE 6+, Firefox 2+, Safari 3+ (and presumably Opera but I did not test)
This script depends on Prototype but could be easily adapted to another library or to stand alone.
$(document).observe('dom:loaded', function(e) {
var browser = {
trident: !!document.all && !window.opera,
webkit: (!(!!document.all && !window.opera) && !document.doctype) ||
(!!window.devicePixelRatio && !!window.getMatchedCSSRules)
};
// Select form elements that won't bubble up delegated events (eg. onchange)
var inputs = $('form_id').select('select, input[type="radio"], input[type="checkbox"]');
$('form_id').observe('submit', function(e) {
// Don't bother submitting if form not modified
if(!$('form_id').hasClassName('modified')) {
e.stop();
return false;
}
$('form_id').addClassName('saving');
});
var change = function(e) {
// Paste event fires before content has been pasted
if(e && e.type && e.type == 'paste') {
arguments.callee.defer();
return false;
}
// Check if event actually results in changed data
if(!e || e.type != 'change') {
var modified = false;
$('form_id').getElements().each(function(element) {
if(element.tagName.match(/^textarea$/i)) {
if($F(element) != element.defaultValue) {
modified = true;
}
return;
} else if(element.tagName.match(/^input$/i)) {
if(element.type.match(/^(text|hidden)$/i) && $F(element) != element.defaultValue) {
modified = true;
} else if(element.type.match(/^(checkbox|radio)$/i) && element.checked != element.defaultChecked) {
modified = true;
}
}
});
if(!modified) {
return false;
}
}
// Mark form as modified
$('form_id').addClassName('modified');
// Enable submit/reset buttons
$('reset_button_id').removeAttribute('disabled');
$('submit_button_id').removeAttribute('disabled');
// Remove event handlers as they're no longer needed
if(browser.trident) {
$('form_id').stopObserving('keyup', change);
$('form_id').stopObserving('paste', change);
} else {
$('form_id').stopObserving('input', change);
}
if(browser.webkit) {
$$('#form_id textarea').invoke('stopObserving', 'keyup', change);
$$('#form_id textarea').invoke('stopObserving', 'paste', change);
}
inputs.invoke('stopObserving', 'change', arguments.callee);
};
$('form_id').observe('reset', function(e) {
// Unset form modified, restart modified check...
$('reset_button_id').writeAttribute('disabled', true);
$('submit_button_id').writeAttribute('disabled', true);
$('form_id').removeClassName('modified');
startObservers();
});
var startObservers = (function(e) {
if(browser.trident) {
$('form_id').observe('keyup', change);
$('form_id').observe('paste', change);
} else {
$('form_id').observe('input', change);
}
// Webkit apparently doesn't fire oninput in textareas
if(browser.webkit) {
$$('#form_id textarea').invoke('observe', 'keyup', change);
$$('#form_id textarea').invoke('observe', 'paste', change);
}
inputs.invoke('observe', 'change', change);
return arguments.callee;
})();
window.onbeforeunload = function(e) {
if($('form_id').hasClassName('modified') && !$('form_id').hasClassName('saving')) {
return 'You have unsaved content, would you really like to leave the page? All your changes will be lost.';
}
};
});
I would store each fields value in a variable when the page loads, then compare those values when the user unloads the page. If any differences are detected you will know what to save and better yet, be able to specifically tell the user what data will not be saved if they exit.
// this example uses the prototype library
// also, it's not very efficient, I just threw it together
var valuesAtLoad = [];
var valuesOnCheck = [];
var isDirty = false;
var names = [];
Event.observe(window, 'load', function() {
$$('.field').each(function(i) {
valuesAtLoad.push($F(i));
});
});
var checkValues = function() {
var changes = [];
valuesOnCheck = [];
$$('.field').each(function(i) {
valuesOnCheck.push($F(i));
});
for(var i = 0; i <= valuesOnCheck.length - 1; i++ ) {
var source = valuesOnCheck[i];
var compare = valuesAtLoad[i];
if( source !== compare ) {
changes.push($$('.field')[i]);
}
}
return changes.length > 0 ? changes : [];
};
setInterval(function() { names = checkValues().pluck('id'); isDirty = names.length > 0; }, 100);
// notify the user when they exit
Event.observe(window, 'beforeunload', function(e) {
e.returnValue = isDirty ? "you have changed the following fields: \r\n" + names + "\r\n these changes will be lost if you exit. Are you sure you want to continue?" : true;
});
I've used dirtyforms.js. Works well for me.
http://mal.co.nz/code/jquery-dirty-forms/
To alert the user before closing, use unbeforeunload:
window.onbeforeunload = function() {
return "You are about to lose your form data.";
};
I did some Cross Browser Testing.
On Chrome and Safari this is nice:
<form onchange="validate()">
...
</form>
For Firefox + Chrome/Safari I go with this:
<form onkeydown="validate()">
...
<input type="checkbox" onchange="validate()">
</form>
Items like checkboxes or radiobuttons need an own onchange event listener.
Attach an event handler to each form input/select/textarea's onchange event. Setting a variable to tell you if you should enable the "save" button. Create an onunload hander that checks for a dirty form too, and when the form is submitted reset the variable:
window.onunload = checkUnsavedPage;
var isDirty = false;
var formElements = //Get a reference to all form elements
for(var i = 0; len = formElements.length; i++) {
//Add onchange event to each element to call formChanged()
}
function formChanged(event) {
isDirty = false;
document.getElementById("savebtn").disabled = "";
}
function checkUnsavedPage() {
if (isDirty) {
var isSure = confirm("you sure?");
if (!isSure) {
event.preventDefault();
}
}
}
Here's a full implementation of Dylan Beattie's suggestion:
Client/JS Framework for "Unsaved Data" Protection?
You shouldn't need to store initial values to determine if the form has changed, unless you're populating it dynamically on the client side (although, even then, you could still set up the default properties on the form elements).
You can also check out this jQuery plugin I built at jQuery track changes in forms plugin
See the demo here and download the JS here
If you are open to using jQuery, see my answer a similar question:
Disable submit button unless original form data has changed.
I had the same challenge and i was thinking of a common solution. The code below is not perfect, its from initial r&d. Following are the steps I used:
1) Move the following JS to a another file (say changeFramework.js)
2) Include it in your project by importing it
3) In your html page, whichever control needs monitoring, add the class "monitorChange"
4) The global variable 'hasChanged' will tell, if there is any change in the page you working on.
<script type="text/javascript" id="MonitorChangeFramework">
// MONITOR CHANGE FRAMEWORK
// ALL ELEMENTS WITH CLASS ".monitorChange" WILL BE REGISTERED FOR CHANGE
// ON CHANGE IT WILL RAISE A FLAG
var hasChanged;
function MonitorChange() {
hasChanged = false;
$(".monitorChange").change(function () {
hasChanged = true;
});
}
Following are the controls where I used this framework:
<textarea class="monitorChange" rows="5" cols="10" id="testArea"></textarea></br>
<div id="divDrinks">
<input type="checkbox" class="chb monitorChange" value="Tea" />Tea </br>
<input type="checkbox" class="chb monitorChange" value="Milk" checked='checked' />Milk</br>
<input type="checkbox" class="chb monitorChange" value="Coffee" />Coffee </br>
</div>
<select id="comboCar" class="monitorChange">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<button id="testButton">
test</button><a onclick="NavigateTo()">next >>> </a>
I believe there can be huge improvement in this framework. Comment/Changes/feedbacks are welcome. :)