最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Standard way to detect form values has been changed? - Stack Overflow

programmeradmin3浏览0评论

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 pare 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

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 pare 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

Share Improve this question edited Jun 23, 2015 at 7:05 Mahendran asked Jun 23, 2015 at 6:31 MahendranMahendran 4868 silver badges20 bronze badges 2
  • are you using jQuery?? – Girish Commented Jun 23, 2015 at 6:50
  • Duplicate of Generic way to detect if html form is edited. – Dan Dascalescu Commented Apr 11, 2024 at 21:20
Add a ment  | 

3 Answers 3

Reset to default 3

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 ment: If you want to pare form data with default value then store default form value in data-* attribute and pare 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./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>

You can pare 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.

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 plete your task easily.

发布评论

评论列表(0)

  1. 暂无评论