简体   繁体   中英

Get initial form value with javascript

I have a php generated form like this

<form onsubmit="formSubmit(this)" method="post"> 
    Product Name <input name="prID" type=" text" value="poney" readonly></input>
    Platform Name<input name="platform" type="text" value="Jambon"></input>
    <input  type="submit" value="OK">   
    <input type="reset" value="Cancel">
</form>

Ok so now if you click on Cancel, your form is reset and the value of input are reset to the initial value. What I want to do is get the form intial value in my formSubmit(this) function.

if a I do something like

formSubmit(form){
    alert(form[0].value+form[1].value); 
}

the output will be something like " poney what ever you type " what I want is

formSubmit(form){
    alert(form[0].value+" old value: "form[1].initialvalue+" new value: "+form[1].value); 
 }

which is supposed to give output like this " poney old value: jambon new value: whatever "

Do you know a way of getting those information, as it seems that they are stored somewhere?

Easiest way is to just save it on document load (unless it's being populated by AJAX or some other post-load event; then you'd have to store the initial state there).

<script>
  $(function(){
    var $form = $('form'),
        formOriginalValue;

    // store initial state on page load
    formOriginalValue = $form.serializeArray();

    // catch the submit handler and compare
    $form.submit(function(e){
      // given 'element1' is a text box:
      //
      // original value: formOriginalValue['element1']
      //      new value: $('[name="element1"]', this).val();
    });
  });
</script>

另一个解决方案可能是使用data-*属性 ,jQuery具有内置的data()函数以管理这些数据。

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