0

I have a form that is similar to this:

<fieldset id="user">
  <input type="text" id="firstName">
  <input type="text" id="lastName">
</fieldset>

Then I do an Ajax call to fill the values of those two fields. At this point I want to save the current state of the form (with the populated values) in case the user needs to revert back after making a change.

I've tried this:

$("#user").clone(true).html()

As well as this:

$("#user").html()

both return the original html from the dom that was created before the fields were populated. Is there a way to grab the html with the values after they have been populated with JS?

  • possible duplicate for this question: [http://stackoverflow.com/questions/1388893/jquery-html-in-firefox-uses-innerhtml-ignores-dom-changes](http://stackoverflow.com/questions/1388893/jquery-html-in-firefox-uses-innerhtml-ignores-dom-changes) – jmacboy May 17 '12 at 16:09

2 Answers2

0

You can use the built-in data. Where you do the ajax call, store the value in the data for for the element too:

$.data( $("#firstname"), "value", value );
$.data( $("#lastname"), "value", value );

At the point you want to revert the change:

$("#firstname").val( $.data($("#firstname"), "value") );
$("#lastname").val( $.data($("#lastname"), "value") );

When you revert, you can iterate through x-number of elements too

$("#user input").each( function() {
   $(this).val( $.data($(this), "value") );
});
jwatts1980
  • 7,254
  • 2
  • 28
  • 44
0
var prev = $('#user').html(); // store previous state

$.ajax({
  url: '',
  ....
  ....
  success: function(res) {
    //assume that your res is like:
    /**
    res = {
        firstname: 'FIRSTNAME', 
        lastname : 'LASTNAME'
    }
    */
    $('#user input#firstname').val(res.firstname);
    $('#user input#lastname').val(res.lastname);
  } 
})

//For revert:

$('#user').empty().html(prev);
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • Shouldn't there be a `.` before `val(res.firstname);` and `val(res.last);`? Like that: `$('#user input#firstname').val(res.firstname); $('#user input#lastname').val(res.last);` – Alex May 17 '12 at 16:01