简体   繁体   中英

Standard way to detect form values has been changed?

I need to detect the value changes in from before refreshing page or closing page , i have written function which will trim the form value and concatenate to previous value

function formValue(object) {
        var formValue = "";
        $(object).find("input,select,radio,checkbox,textarea").each(function(){        
            formValue += $(this).val().trim() + "&";
        });
        return formValue.substring(0, formValue.length - 1);
    }
}

i will store the value in oldValue variable on page old.On unloadEvent it will compare old value with new form value

var addEvent = window.attachEvent || window.addEventListener;
var unloadEvent = window.attachEvent ? 'onbeforeunload' : 'beforeunload';

addEvent(unloadEvent, function (e) {

    if(oldvalue!==formValue($("form")){
    retun "Data will lost , Do you wish to continue ?"
    }
});

it is working great , But i have doubt that , Is this standard way to check form value changed or any other best way is available to detect form value changes ?

I need to stop page reload or exit only if value has been changed . i mean if i change the input box value from name to first name and again changes it name . now it should not treat as from value change

You can check form data change or not form more reliable way, it's also easy

var formChangeFlag = false;
$('form').on('change', ':input', function(e){ 
 //':input' selector get all form fields even textarea, input, or select
  formChangeFlag = true;
});

$( window ).unload(function() {
  if(formChangeFlag === true){
     return "Data will lost , Do you wish to continue ?";
   }
});

Update on comment: If you want to compare form data with default value then store default form value in data-* attribute and compare value on field change event.

 var formChangeFlag = false; _$Forminputs = $('form :input:not([type=submit])'); _$Forminputs.on('change', function(e) { //':input' selector get all form fields even textarea, input, or select formChangeFlag = false; //alert(_$Forminputs.length); for (var i = 0; i < _$Forminputs.length; i++) { if ($(_$Forminputs[i]).val() != $(_$Forminputs[i]).data('default')) { formChangeFlag = true; break; } } }); $('input[type=submit]').on('click', function() { if (formChangeFlag === true) { alert('form values changed') } else { alert('form values not changed') } return false; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="" type="post"> <select name="sirnmae" data-default="Mr."> <option value="Mr." selected>Mr.</option> <option value="Miss">Miss</option> </select> <input type="text" data-default="ger" value="ger" name="fname" /> <input type="text" value="last name" data-default="last name" /> <input type="submit" value="post form" /> </form> 

There is a onchange() function which returns the value once the user leaves the input box. This works for several HTML elements. Simply grab the value from the element ex:

<input type="text" onchange="newVar=this.value"/>

Or register an event listener. This should complete your task easily.

You can compare the defaultValue with the current value of all form controls. The only difficulty is select elements, for those you can check if the selected index is -1 (no option selected), 0 (first option selected, the default in nearly every browser) or that the selected option has the selected attribute.

The following does that:

function formChanged(form) {
  return [].every.call(form.elements, function(control) {

    // If a select's selected index is -1 (no option selected),
    // 0 (first option selected) or set to an option that is
    // selected by default, it hasn't changed
    if (control.tagName.toLowerCase() == 'select') {
      var idx = control.selectedIndex;
      return idx == -1 || idx == 0 || control.options[idx].defaultSelected;
    }

    // Otherwise, check current value with default value
    return control.value == control.defaultValue;
  });
}

It won't work for a multiple select that has more than one option set to selected by default (pretty rare), but will work everywhere else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM