views:

494

answers:

4

I am trying to reset the actual value attribute of an input so that it can be reset back to that value if reset, not necessarily the original value when the form was loaded. The problem is these changes don't seem to take effect. I have tried both:

$(this).attr('value', $(this).val());

as well as....

$(this).val($(this).val());

Neither of these actually change the value="" attribute of the input, which is what is used when a form is reset. The problem is that if someone saves a form (via AJAX), then again edits it and presses reset (w/out saving this time), it will go back to the original values the page loaded with, NOT the values last saved with, which is what I'm trying to get. I know there are ways around this (store in local variables or something), but a jQuery solution would be much better. Any ideas??

A: 

when you are doing something like this:

$(this).val($(this).val());

it really translates as:

var temp = $(this).val());
$(this).val(temp);

So in essence, its just putting the same value back in.

What you will want to do is on the document load or the AJAX request, store the value in a variable and then retrieve it when the form is reset.

Daniel A. White
A: 

Just use thing.value="foo"; Check if it works when thing is a jQuery object as well as just a regular DOM object. using attr('value', $(this).val()) won't work how you want it to

CrazyJugglerDrummer
A: 

I've come up with a solution for this...

When saving a form (via AJAX, on the success callback):

// Set 'savedValue' attr on elements (for when reset, will reset to last saved values)
$('#myForm input').each(function() {
    $(this).attr('savedValue', $(this).val());
});

When needing to reset the form:

// Reset form
if($('#myForm input:first').attr('savedValue')!=undefined) {
    // Have saved values, reset to last saved values
    $('#myForm input').each(function() {
     $(this).val($(this).attr('savedValue'));
    });
}
else {
    // No saved values, reset form
    $('#myForm')[0].reset(); 
}

This works great for textboxes, and with a little tweaking you could get it to work with any input type. I've got a lot of inputs so I wanted to avoid manually storing/resetting them if at all possible. This would be a good plugin... maybe tomorrow

Ryan
A: 

Even better than a local variable, you could use the jQuery Data methods to store the reset values along with the element to be reset.

When saving:

$(this).data("ResetValue", $(this).val());

On reset:

$(this).val($(this).data("ResetValue"));

Changing the selectors appropriately, and probably adding the undefined check as Ryan mentioned.

Kevin Gorski